【发布时间】: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