2013-12-24 87 views
0

我創建了一個指令來監聽向上和向下箭頭的按下。但我想提取被按下的鍵。有沒有辦法讓它通過指令?從Angular指令中獲取參數

/** 
* 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用法:

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

爲什麼不使用角度NG-按鍵? – Nix

+0

因爲我不知道....哈哈。謝謝! –

回答

2

您應該使用ng-keypress

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


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

    } 
} 

例撥弄:http://jsfiddle.net/ncapito/3xyr6/

+0

我試過添加這個,但是函數沒有觸發 –

+0

@WilliamFalcon什麼版本的角(在上面加了一個小提琴)? – Nix