Javascript 何时在 Angularjs 中使用 $watch 或 ng-change

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28313865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:36:33  来源:igfitidea点击:

When to use $watch or ng-change in Angularjs

javascriptangularjsangularjs-ng-change

提问by levi

When should I use angular $watchfunctions and when use ng-changeangularjs directive? To me, they both can do the same.

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

Are there any differences or usage patterns between them?

它们之间有什么区别或使用模式吗?

回答by New Dev

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.

但即使在它们的应用中,它们也不同。

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

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

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

使用ng-change,处理程序被显式调用以响应事件。

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

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

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

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

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

还值得指出的是ng-change作品只有与组合ng-model-换句话说,该ng-change表达式只有当评估ngModel.$viewValue(参考ngModelController文档获取更多信息)被改变,这通常发生在响应用户启动的事件。