问题描述
限时送ChatGPT账号..通常 ng-model 会在用户每次按下密钥时更新绑定模型:
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.
在旧版本的 angular 中,有一个 ng-model-instant 指令,它的工作方式与 ng-model 现在的工作方式相同(至少对用户而言 - 我对他们的实现一无所知).因此,在旧版本中,如果我只给 ng-model,它会更新模型 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 用于元素的更改"事件.我不希望它是即时的.这样做的最简单方法是什么?
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.
我需要的是让 ng-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/selbh/EPNRd/
Here is an explanation of what I'm trying to do: http://jsfiddle/selbh/EPNRd/
推荐答案
这里我为你创建了 onChange 指令.演示:http://jsfiddle/sunnycpp/TZnj2/52/
Here I created onChange directive for you. Demo: http://jsfiddle/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 创建 on-change 指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论