AngularJS:使用element.bind('input')在自定义指令中访问事件 [英] AngularJS: Access event inside custom directive using element.bind('input')
问题描述
我必须编写自定义指令,因为在编写韩文字符时我需要访问用户输入。如另一篇文章,我不能使用keydown或keypress,因为在编写韩文字符时它们不会在正确的时间被触发。 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. element.bind('input') does the trick but now I face another problem.
如何在element.bind回调中访问事件以退出/返回if输入键已被击中?
How can I access the event inside the element.bind callback to exit/return if the enter key has been hit?
HTML
<input cst-input="quizzesCtrl.checkAnswer(answer)" name="answer" id="answer" ng-model="quizzesCtrl.answer" type="text" />
指令
.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});
});
});
}
};
})
推荐答案
请注意;
输入:没有哪个属性并在按下后触发。即你可以在keypress事件中绑定unbind input 事件。 Enter也不会触发输入事件。即e.which == 13不需要验证。
input: don't have which property and triggered after keypress. Namely you can bind unbind input event inside keypress event. Also input event don't triggered on Enter. Namely e.which==13 not requred to validate.
keypress 事件在退格时未触发,如果您不需要检查值时退格,没有问题。
keypress event not triggered when backspace, if you don't need check value when backspace, there is no problem.
keydown 和 keyup 事件触发每个键,您可以将它们与其他
一起使用您可以尝试类似这样的事情。
keydown and keyup events triggered for each key you can use them with eachother You can try something like this.
.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')
});
});
}
};
})
这篇关于AngularJS:使用element.bind('input')在自定义指令中访问事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!