Angular JS – Setting a behaviour for a Custom Directive

I can use the link property to set a particular behavior (instead of/along with a template) for a directive. In this example i define the ng-enter directive to handle the pression of the return button in a text box. Within the link function I can use JQuery (is a lite version provided by Angular itself) to define the behavior associated with the directive.

angular.module('angularApp.directives').directive('ngEnter', function () {
    return {
        restrict: "A",
        link: function ($scope, element, attributes) {
            element.bind("keydown keypress", function (event) {
                if (event.which === 13) {
                    $scope.$apply(function () {
                        $scope.$eval(attributes.ngEnter, { 'event': event });
                    });
                    event.preventDefault();
                }
            });
        }
    }
});

And this is the directive usage:

<input class="search-text" type="text" data-ng-model="searchText" data-ng-enter="Search()" placeholder="Search" />

Leave a comment