角度ng变化与ng模型性能 [英] Angular ng-change vs ng-model performance
问题描述
在输入中使用ng-change而不是ng-model是否有任何性能提升?
Is there any performance improvement in using ng-change in an input instead of ng-model?
我在输入中使用ng-model时,然后一个$ watch(或类似的)由变量中的angular组成,这增加了工作量。
I pressume that when ng-model is used in an input, then a "$watch" (or similar) is made by angular in a variable, and that adds work load.
但如果使用ng-change,那么变量(模型)可以在需要时更新,只有当输入改变了这个变量时才能执行代码。
But if ng-change is used, then the variable (model) can be updated when needed, code can be executed only when this variable is changed by the input.
这假设只有一个输入可以改变变量。
This works assuming that only one input can change a variable.
示例如下:
<input type="text" ng-model="ElTexto">
<div ng-show="ElTexto"></div>
使用ng-change
html
using ng-change
html
<input type="text" ng-change="elTexto()">
<div ng-show="ElTexto"></div>
js
$scope.elTexto(){
$scope.ElTexto = true;
}
推荐答案
ng-change
需要 ng-model
,因此您无法在两者之间进行选择。您必须使用 ng-model
,如果愿意,还可以使用 ng-change
。
ng-change
requires ng-model
, so you can't choose between the two. You must use ng-model
, and can also use ng-change
if you wish.
请注意,两者非常不同。 ng-model
将保持您的输入值和支持模型完美同步; ng-change
将指示用户正在与输入进行交互。如果你关心他们正在改变的价值,比如你正在做自动完成,只需使用 ng-model
并让你所有的代码共享同一个变量。如果您特别想在输入更改时执行操作,无论值是什么,那么您可以使用 ng-change
。
Be aware that the two are VERY different. ng-model
will keep your input's value and its backing model in perfect sync; ng-change
will indicate that the user is interacting with the input. If you care about the value they're changing, like if you're doing autocomplete, just use ng-model
and have all your code share the same variable. If you specifically want to take an action when the input changes, regardless of what the value is, then you can use ng-change
for that.
这篇关于角度ng变化与ng模型性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!