Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

javascript - When to use $watch or ng-change in 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 $watch the watched expression will be evaluated on every digest cycle, and if there is a change, the handler is invoked.

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.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...