Dailycode.info

Short solution for short problems

AngularJS: trigger click on 'Enter' in input

Some time ago I wrote a directive to get the Enter key to trigger a function on the controller. It looks like this:

 .directive('keyBind', ['keyCodes', function (keyCodes) {
        function map(obj) {
            var mapped = {};
            for (var key in obj) {
                var action = obj[key];
                if (keyCodes.hasOwnProperty(key)) {
                    mapped[keyCodes[key]] = action;
                }
            }
            return mapped;
        }
        return function (scope, element, attrs) {
            var bindings = map(scope.$eval(attrs.keyBind));
            element.bind("keypress", function (event) {
                if (bindings.hasOwnProperty(event.which)) {
                    scope.$apply(function ()
                    {
                        console.log(event);
                        scope.$eval(bindings[event.which]);
                    });
                }
            });
        };
    }]);

and it used like this:

<input type="text" class="form-control" data-ng-model="playerText" name="player" placeholder="Speler naam" aria-describedby="basic-addon1" key-bind="{ enter: 'addPlayer()'}">

But this can be a lot easier using the ng-keyup directive by angular:

<input ng-keyup="$event.keyCode == 13 && $ctrl.save()" ng-model="$ctrl.editName" placeholder="name" class="form-control" />

It's the same method thats called on this button:

<button type="button" ng-click="$ctrl.save()" class="btn btn-primary">Save</button>

So in stead of writing my own directive, we can just use ng-keyup.