Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch a return on an input element using Aurelia?

Tags:

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 basically once I have finished typing my text to search on, when I pressed the enter key the search function on my controller would run.

How would I do this in Aurelia?

I am still learning about its features so any help would be appreciated.

like image 430
JD. Avatar asked Apr 17 '15 02:04

JD.


2 Answers

I think an alternative to the angular ngEnter would be:

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()"/>
like image 66
Kamil Rostkowski Avatar answered Nov 05 '22 20:11

Kamil Rostkowski


The simplest way would be to wrap the input in a form element and bind to the submit event of the form.

<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>

This will give you the same behavior you have built above. I'm still working to create an example of a custom attribute to do this, but honestly, this is how I would recommend you do this specific thing (capturing when the user presses enter).

like image 44
Ashley Grant Avatar answered Nov 05 '22 20:11

Ashley Grant