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" />
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s