William Falcon
William Falcon

Reputation: 9813

Get parameter from Angular directive

I created a directive to listen to arrow up and down presses. But I want to extract the key that was pressed. Is there a way to pass it through the directive?

/**
 * Call a function when down and up arrow keys are pressed
 */
directives.directive('arrowKey', function() {
    return function(scope, element, attrs) {
        element.bind("keydown keypress", function(event) {

            //Arrow down
            if(event.which === 40) {

                scope.$apply(function(){
                    scope.$eval(attrs.arrowKey);
                });

                event.preventDefault();

            //Arrow Up
            }else if (event.which === 38){
                scope.$apply(function(){
                    scope.$eval(attrs.arrowKey);
                });

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

HTML usage:

<input id="search" type="text" placeholder="Search" class="searchBox" ng-model = "searchText" ng-change = "getAutoCompleteSuggestions(searchText)" ng-enter="getMore(searchText)" arrow-key="arrowPressed(arg)"/>

Upvotes: 0

Views: 161

Answers (1)

Nix
Nix

Reputation: 58552

You should be using ng-keypress.

<input id="search" type="text" ng-keypress='keypress($event)' />


/* ctrl */
$scope.keypress = function($event){
  //check event here. 
  if($event.keyCode == 38){

  }
}

Example fiddle: http://jsfiddle.net/ncapito/3xyr6/

Upvotes: 2

Related Questions