gpt4 book ai didi

javascript - 指令未在 按键上触发

转载 作者:行者123 更新时间:2023-11-30 12:09:35 25 4
gpt4 key购买 nike

我正在关注 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() 告诉我我的指令不能是正确设置为在我按下该元素时触发。

最佳答案

您在传递指令属性时输入了方法名称错误。该方法也应该在 Controller 的 $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;

关于javascript - 指令未在 <Enter> 按键上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34188674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com