输入空格时如何触发 ng-change? [英] How can I trigger ng-change when a space is entered?
问题描述
我有一个函数,当 textarea 的值发生变化时会调用该函数.它工作得很好,除非按下空格键,然后什么都不调用.有没有办法激活这个?从技术上讲,内容正在发生变化,我希望无论如何调用该函数.
I have a function that is called when a textarea's value is changed. It works great, except when the spacebar is pressed, then nothing is called. Is there a way to activate this? Technically, the content is changing, and I would like the function to be called regardless.
我附上了一段代码.您可以看到 $scope.log
数组在按下空格键时不会推送新元素(输入键也是如此),但它会推送任何其他非空格键.
I am attaching a fiddle with the code. You can see the $scope.log
array does not push a new element when the spacebar is pressed (enter key as well), but it does with any other key that is not white space.
小提琴示例:http://jsfiddle.net/UJWLN/4/
推荐答案
您可以在输入中使用指令 ng-trim 并将其设置为 false,如下所示:
You can use the directive ng-trim in your input and set it to false, like this:
<textarea ng-change="changeFunction()" ng-model="myModel" ng-trim="false"></textarea>
但这并不适用于所有情况.如果您希望在每次击键时执行某些操作,请尝试使用自定义指令.我为你写了一篇:
But this won't work for every case. If you want something to be executed on every single keystroke, try with a custom directive. I wrote one for you:
myApp.directive('ngKeystroke', function(){
return {
restrict: 'A',
link: function(scope, elem, attrs){
elem.bind("keyup", function(){
scope.log.push('called');
scope.$digest();
});
}
};
});
这篇关于输入空格时如何触发 ng-change?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!