如何让 ng-model 不立即更新? [英] How to let ng-model not update immediately?
问题描述
代码:
<input type="text" ng-modal="name" />
{{name}}
当我在 input
中输入一些东西时,下面的 {{name}}
会立即改变.是否可以配置它只在我输入所有字符并离开输入后更新name
?
When I input something into the input
, the following {{name}}
will change immediately. Is it able to configure it only update the name
after I input all characters and leave the input?
推荐答案
更新
正如许多人提到的,Angular 现在使用 ng-model-options
指令内置了对此的支持.查看更多此处.
As many have mentioned Angular now has built-in support for this using the ng-model-options
directive. See more here.
<input type="text" ng-model="name" ng-model-options="{updateOn: 'blur'}" />
下面的旧答案:
ng-model 没有内置选项来改变这种行为,但你可以编写一个自定义指令来做到这一点.@Gloopy 写了一个这样的指令另一个问题.你可以在这里查看小提琴.
There's no built-in option for ng-model to change that behaviour, but you can write a custom directive doing it. @Gloopy wrote a directive like that for another question. You can look at the fiddle here.
指令从 input
和 keydown
事件中注销,这些事件在每次击键后触发更新.
The directive unregisters from the input
and keydown
events which trigger the update after each keystroke.
<input type="text" ng-model="name" ng-model-onblur />
更新:
更新了 fiddle 以使用最新的稳定版 AngularJS(撰写本文时为 1.2.16),而不是直接引用 github 上的主版本.
Updated fiddle to use latest stable AngularJS (1.2.16 as of writing), instead of directly referencing the master version at github.
还添加了明确的优先级,以便指令在 ng-model
之后运行,以确保正确更改事件侦听器.
Also added an explicit priority so that the directive is run after ng-model
to ensure event listeners are changed correctly.
这篇关于如何让 ng-model 不立即更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!