How to catch return on input element using Aurelia?

In angularjs, I had the following:

app.directive('ngEnter', function () {
   return function (scope, element, attrs) {
    element.bind("keydown keypress", function (event) {
        if(event.which === 13) {
            scope.$apply(function (){
                scope.$eval(attrs.ngEnter);
            });

            event.preventDefault();
        }
    });
  };
});

And the html was:

<input type="text" ng-model="searchText" class="form-control"
                               placeholder="Search"
                               ng-enter="search($event, searchText)">

So, as soon as I finished typing for the search, when I pressed the enter key, the search function on my controller will start.

How can I do this in Aurelia?

I still find out about its capabilities, so any help would be appreciated.

+4
source share
4 answers

The easiest way is to wrap inputin an element formand bind to a submitform event .

<form role="form" submit.delegate="search()">
  <div class="form-group">
    <label for="searchText">Search:</label>
    <input type="text" value.bind="searchText" 
           class="form-control" id="searchText" 
           placeholder="Search">
  </div>
  <button type="submit" class="btn btn-default">Submit</button>
</form>

, . , , , (, ).

+12

, angular ngEnter :

import {customAttribute, inject} from 'aurelia-framework';

@customAttribute('enter-press')
@inject(Element)
export class EnterPress {
    element: Element;
    value: Function;
    enterPressed: (e: KeyboardEvent) => void;

    constructor(element) {
        this.element = element;

        this.enterPressed = e => {
            let key = e.which || e.keyCode;
            if (key === 13) {
                this.value();//'this' won't be changed so you have access to you VM properties in 'called' method
            }
        };
    }

    attached() {
        this.element.addEventListener('keypress', this.enterPressed);
    }

    detached() {
        this.element.removeEventListener('keypress', this.enterPressed);
    }
}
<input type="password" enter-press.call="signIn()"/>
Hide result
+11

, , . , :

  • Add a hidden submit button at the top of my form with the attribute click.delegate.
  • . , , .

Hope this helps, Andrew

EDIT:

You can also add a keypress event delegate:

<input keypress.delegate="doSomething($event)" />

And define doSomething () as:

doSomething(event) {
  if(event.which == 13) {
    alert('Your code goes here!');
  }
  event.preventDefault();
}

This will be a little cleaner if you have a lot of input with different types of keystrokes.

+3
source

Due to keypress.delegateand keypress.triggerin the block <input>that enters the default text, your function must return true to avoid this, for example:

doSomething(event) {
    if(event.which == 13) {
        console.log('Your code goes here!');
        event.preventDefault();
        return false;
    }
    return true;
}
+1
source

All Articles