当使用$手表或NG-变化Angularjs [英] When to use $watch or ng-change in Angularjs

查看:122
本文介绍了当使用$手表或NG-变化Angularjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题:什么时候应该使用角 $观看功能,当使用 NG-变化 angularjs指令?对我来说,它们都可以这样做。

I have a question: When should I use angular $watch functions and when use ng-change angularjs directive? To me, they both can do the same.

它们之间有任何分歧或使用模式?

Are there any differences or usage patterns between them?

推荐答案

他们是不一样的,清晰。一个是在所述控制器单独使用;另一种是一个输入元件上的指令。

They are not the same, clearly. One is used solely in the controller; the other is a directive on an input element.

但是,即使在应用它们之间的区别。

But even in their application they differ.

当您使用 $腕表的看着前pression将在每一个消化周期评估,如果有变化,处理程序被调用。

When you use $watch the watched expression will be evaluated on every digest cycle, and if there is a change, the handler is invoked.

使用 NG-变化,处理程序以响应事件显式调用。

With ng-change, the handler is invoked explicitly in response to an event.

使用 $观看,变化可以来自任何地方:用户操作,控制器的功能,服务 - 都将触发处理程序

With $watch, change can come from anywhere: user action, controller function, service - all will trigger the handler.

使用 NG-变化,变化仅限于一个特定的输入元件上的用户操作。

With ng-change, the change is restricted to a user action on a particular input element.

值得也需要注意的是 NG-变化作品的结合 NG-模型 - 换句话说,在 NG-变化前pression进行评估,只有当 ngModel $ viewValue (参见<一个href=\"https://docs.angularjs.org/api/ng/type/ngModel.NgModelController\"><$c$c>ngModelController对于更多的信息文档)被改变,其通常发生在响应于用户启动的事件。

It is worth to note also that ng-change works only in combination with ng-model - in other words, the ng-change expression is evaluated only when ngModel.$viewValue (refer to ngModelController documentation for more info) is changed, which typically happens in response to a user-initiated event.

这篇关于当使用$手表或NG-变化Angularjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆