如何为AngularJS创建换行指令? [英] How to create on-change directive for AngularJS?
问题描述
通常ng模型更新绑定模型每次用户按下键:
Normally ng-model updates bound model each time user pushes the key:
<input type="text" ng-model="entity.value" />
这几乎在所有情况下都很好用。
This works great in almost every case.
但是我需要它来更新onchange事件发生时,而不是onkeyup / onkeydown事件。
But I need it to update when onchange event occurs instead when onkeyup/onkeydown event.
在旧版本的角色中,有一个ng-model-instant指令工作与ng-model相同,现在(至少对于用户来说,我不了解它们的实现)。
所以在旧版本中,如果我只是给了ng模型,它正在更新模型onchange,当我指定ng-model-instant它正在更新模型onkeypup。
In older versions of angular there was a ng-model-instant directive which worked same as ng-model works now (at least for the user - i don't know anything about their implementations). So in older version if I just gave ng-model it was updating the model onchange and when I specified ng-model-instant it was updating the model onkeypup.
现在我需要使用ng-model来使用元素的change事件。我不想让它瞬间最简单的方式是这样做?
Now I need ng-model to use on "change" event of the element. I don't want it to be instant. What's the simplest way of doing this?
编辑
以反映模型的任何其他更改 - 如果模型将在其他位置更新,输入值应反映此更改。
The input still has to reflect any other changes to the model - if the model will be updated in other place, value of the input should reflect this change.
我需要的是具有-model指令的工作就像在老版本的angularjs中一样。
What I need is to have ng-model directive to work just like it worked in the older versions of angularjs.
这是一个解释我要做的事情:
http://jsfiddle.net/selbh/EPNRd/
Here is an explanation of what I'm trying to do: http://jsfiddle.net/selbh/EPNRd/
推荐答案
这里我为你创建了onChange指令。 演示: http://jsfiddle.net/sunnycpp/TZnj2/52/
Here I created onChange directive for you. Demo: http://jsfiddle.net/sunnycpp/TZnj2/52/
app.directive('onChange', function() {
return {
restrict: 'A',
scope:{'onChange':'=' },
link: function(scope, elm, attrs) {
scope.$watch('onChange', function(nVal) { elm.val(nVal); });
elm.bind('blur', function() {
var currentValue = elm.val();
if( scope.onChange !== currentValue ) {
scope.$apply(function() {
scope.onChange = currentValue;
});
}
});
}
};
});
这篇关于如何为AngularJS创建换行指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!