我创建了一个指令来监听向上和向下箭头的按下。但我想提取按下的键。有没有办法通过指令传递它?
/**
* 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)"/>
最佳答案
您应该使用ng-keypress .
<input id="search" type="text" ng-keypress='keypress($event)' />
/* ctrl */
$scope.keypress = function($event){
//check event here.
if($event.keyCode == 38){
}
}
fiddle 示例:http://jsfiddle.net/ncapito/3xyr6/
关于javascript - 从 Angular 指令获取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20753473/