我为我的 AngularJS 应用程序编写了一个指令,用于计算文本区域中的单词数量,如果它低于确定的阈值,我将 ng-valid 项设置为 false。一切都很好,但是当用户选择文本区域中的部分或全部文本,然后使用退格键或删除按钮删除所选内容时,字数统计似乎不起作用。如何捕捉这个事件?我的指令如下,我认为绑定(bind)到 onmouseup
事件将涵盖这样的场景:
.directive('wordCount', function () {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function (scope, element, attrs, ngModel) {
// do nothing if no ng-model
if (!ngModel) {
return;
}
// scope.minWordCount is taken from the scope!!!! We repeat this so put into reuseabe function
if (!scope.minWordCount) {
return;
}
function checkWordCount() {
if (element[0].value === '') {
scope.wordCount = 0;
} else {
scope.wordCount = element[0].value.replace(/\s+/gi, ' ').split(' ').length;
}
// replace the numbers by finding the first space
scope.wordCountText = scope.wordCount + ' ' + scope.wordCountText.substr(scope.wordCountText.indexOf(' ') + 1);
if(scope.wordCount > scope.minWordCount - 1) {
ngModel.$setValidity('wordcount', true);
} else {
ngModel.$setValidity('wordcount', false);
}
}
var page = angular.element(window);
page.bind('load', function () {
checkWordCount();
});
// Listen for change events to enable binding
element.bind('blur keyup keydown keypress click change focus onmouseup', function () {
checkWordCount();
});
}
};
})
;
最佳答案
我建议您使用更简单的方法来执行此操作,即使用 ngModel 的 $viewChangeListeners 属性。
这是一个工作示例,希望对您有所帮助
http://plnkr.co/edit/aZtl2hoEaXrkZCRAR9RH?p=preview
directive('wordCounter', function() {
return {
require: 'ngModel',
link: function($scope, $node, attributes, controller) {
function countWord(string) {
return string.split(' ').length;
}
controller.$viewChangeListeners.push(function(){
console.log(countWord(controller.$modelValue))
})
}
}
});
关于javascript - 用户选择文本并按删除/退格键时不会触发字数统计的 AngularJS 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25378862/