[英]AngularJS: Access event inside custom directive using element.bind('input')
I had to write a custom directive because I need access to user input while composing Korean characters. 我必须编写一个自定义指令,因为在编写韩文字符时需要访问用户输入。 As explained in another post , I can't use keydown or keypress because they don't get triggered at the right time when composing Korean characters.
如另一篇文章中所述 ,我不能使用keydown或keypress,因为在编写韩文字符时不会在正确的时间触发它们。 element.bind('input') does the trick but now I face another problem.
element.bind('input')可以解决问题,但现在我面临另一个问题。
How can I access the event inside the element.bind callback to exit/return if the enter key has been hit? 如果按下回车键,如何访问element.bind回调内部的事件以退出/返回?
HTML 的HTML
<input cst-input="quizzesCtrl.checkAnswer(answer)" name="answer" id="answer" ng-model="quizzesCtrl.answer" type="text" />
Directive 指示
.directive('cstInput', function() {
return {
restrict: 'A',
require: '^ngModel',
link: function (scope, element, attrs, ngModel) {
element.bind('input', function(event) {
if (event.which === 13) { return; } // can't access the event unless I bind to keypress etc
scope.$apply(function(){
scope.ngModel = element.val();
scope.$eval(attrs.cstInput, {'answer': scope.ngModel});
});
});
}
};
})
Please note that; 请注意;
input: don't have which property and triggered after keypress. 输入:没有哪个属性,并在按键后触发。 Namely you can bind unbind input event inside keypress event.
也就是说,您可以将取消绑定的输入事件绑定到keypress事件中。 Also input event don't triggered on Enter.
输入事件也不会在Enter上触发。 Namely e.which==13 not requred to validate.
即e.which == 13不需要验证。
keypress event not triggered when backspace, if you don't need check value when backspace, there is no problem. 退格时不会触发keypress事件,如果退格时不需要检查值,就没有问题。
keydown and keyup events triggered for each key you can use them with eachother You can try something like this. 您可以将每个按键触发的keydown和keyup事件彼此配合使用。您可以尝试这样的操作。
.directive('cstInput', function() {
return {
restrict: 'A',
require: '^ngModel',
link: function (scope, element, attrs, ngModel) {
element.on('keypress', function(event) {
if (event.which === 13) { return; } // check key how you want
//attach input event
element.on('input', function(evt) {
scope.$apply(function(){
scope.ngModel = element.val();
scope.$eval(attrs.cstInput, {'answer': scope.ngModel});
});
//deatach event again
element.off('input')
});
});
//Alternatively using keydown with same way
element.on('keydown', function(event) {
if (event.which === 13) { return; } // check key how you want
//attach input event
element.on('input', function(evt) {
scope.$apply(function(){
scope.ngModel = element.val();
scope.$eval(attrs.cstInput, {'answer': scope.ngModel});
});
//deatach event again
element.off('input')
});
});
}
};
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.