【问题标题】:directive not firing on <Enter> keypress指令未在 <Enter> 按键上触发
【发布时间】:2015-12-09 20:48:53
【问题描述】:

我关注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>

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

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope angularjs-controller


    【解决方案1】:

    在传递指令属性时,您的方法名称拼写错误。该方法也应该在控制器的$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;
    

    【讨论】:

      猜你喜欢
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 2014-02-09
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多