何时在 Angularjs 中使用 $watch 或 ng-change [英] When to use $watch or ng-change in Angularjs

查看:29
本文介绍了何时在 Angularjs 中使用 $watch 或 ng-change的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我什么时候应该使用 angular $watch 函数,什么时候使用 ng-change angularjs 指令?对我来说,他们都可以做同样的事情.

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.

当您使用 $watch 时,监视的表达式将在每个摘要周期上进行评估,如果有更改,则调用处理程序.

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-change,处理程序被显式调用以响应事件.

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

使用 $watch,更改可以来自任何地方:用户操作、控制器功能、服务 - 所有这些都会触发处理程序.

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

使用 ng-change,更改仅限于用户对特定输入元素的操作.

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

还值得注意的是,ng-changeng-model 结合使用 - 换句话说,ng-change 表达式仅在 ngModel.$viewValue 时被评估(参考 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.

这篇关于何时在 Angularjs 中使用 $watch 或 ng-change的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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