指令未在 <Enter> 按键时触发

directive not firing on <Enter> keypress

我正在关注 this SO Post 创建 Enter 按键指令。

这是我的 JS,我在其中模拟了相同的功能:

JavaScript

var app = angular.module('myApp', []);
app.controller('MainCtrl', ['$scope', function($scope) {
  $scope.greeting = 'Hola!';
}]);
app.directive('myEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
               scope.$apply(function (){
                scope.$eval(attrs.myEnter);
            });

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

});

function callServerWithSong(){
 alert("calling!");
}

HTML

<div id="search" ng-app="myApp" ng-controller="MainCtrl">
   <input type="text" id="search" my-enter="calServerWithSong()">
</div>

问题是,当我select输入框,输入一个字符串并回车时,它不报错,也不执行alert(),它告诉我我的指令不能正确设置为在我按下该元素时触发。

您在传递指令属性时输入了方法名称错误。该方法也应该在控制器的 $scope 中。

HTML

<div id="search" ng-app="myApp" ng-controller="MainCtrl">
   <input type="text" id="search" my-enter="callServerWithSong()">
</div>

代码

function callServerWithSong(){
 alert("calling!");
}

$scope.callServerWithSong = callServerWithSong;