2015-06-01 39 views
1

我想,當Escape鍵被按下寫一個AngularJS指令運行功能:AngularJS按鍵時的鍵碼指令

HTML

<input type="text" custom-keypress="consoleLog()"> 

JS

var app = angular.module('app', []); 

app.controller('appCtrl', function($scope) { 
    $scope.consoleLog = function() { 
    console.log('works') 
    } 
}); 

app.directive('customKeypress', function() { 
    return function (scope, element, attrs) { 
     element.bind("keydown keypress", function (event) { 
      if(event.which === 27) { 
       scope.$apply(function(){ 
        scope.$eval(attrs.ngEnter); 
       }); 

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

不幸的是,當我按下Escape鍵時沒有任何反應。

Here's my Plunker

任何想法我做錯了什麼?

+1

你有一個錯字有...'ngEnter' V/S'customKeypress'? – PSL

+0

嘗試刷新plunk - 應該是'custom-keypress'和'customKeypress' – Ryan

回答

0

它不起作用,因爲您沒有ng-enter屬性。它應該是:

scope.$eval(attrs.customKeypress); 
+0

嘗試刷新plunk - 應該是'custom-keypress'和'customKeypress' – Ryan