Javascript 指令未在<;输入>;按键
我正在创建一个enterkeypress指令 这是我的JS,我在其中模拟了相同的功能: JavaScriptJavascript 指令未在<;输入>;按键,javascript,angularjs,angularjs-directive,angularjs-scope,angularjs-controller,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,Angularjs Controller,我正在创建一个enterkeypress指令 这是我的JS,我在其中模拟了相同的功能: JavaScript var app = angular.module('myApp', []); app.controller('MainCtrl', ['$scope', function($scope) { $scope.greeting = 'Hola!'; }]); app.directive('myEnter', function () { return function (scope
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();
}
});
};
}))
HTML
<div id="search" ng-app="myApp" ng-controller="MainCtrl">
<input type="text" id="search" my-enter="calServerWithSong()">
</div>
<div id="search" ng-app="myApp" ng-controller="MainCtrl">
<input type="text" id="search" my-enter="callServerWithSong()">
</div>
问题是,当我选择输入框,键入字符串并按enter键时,它不会报告错误或执行
alert()
,这告诉我,我的指令不能正确设置为在按下该元素时触发 在传递指令属性时,方法名输入错误。该方法也应存在于控制器的$scope
中
HTML
<div id="search" ng-app="myApp" ng-controller="MainCtrl">
<input type="text" id="search" my-enter="calServerWithSong()">
</div>
<div id="search" ng-app="myApp" ng-controller="MainCtrl">
<input type="text" id="search" my-enter="callServerWithSong()">
</div>