问题
I tried to find some good examples on best practice in moving $watch
functions from a controller to a factory, for example.
What I have found is that actually there isn't a unanimous opinion on what's best to do. I've seen examples of injection the $rootScope
into a factory and $watch
ing for value changes there.
Another suggestion is to avoid them whenever possible, and to use ngChange
instead on the element itself, for example:
<div ng-model="foo.bar" ng-change="updateValue(foo.bar)"></div>
What is your proposed way? I've been putting $watch
es in my controllers ever since I started learning AngularJS but now I want to embrace best practice approaches, trying to make and keep my controllers as thin as possible.
回答1:
I guess where to put $watch
heavily depends on the use-case scenario. The most important thing to be careful about $watch
is not to do any hard-work inside the handle function especially if what you are watching is changing a lot; that would highly damper your performance. And be sure that in your handle function you don't change something else which is already being watched as this will cause a chain of change updates.
If you are sure that the variable you are watching can only be changed from one place, it is better idea to use ng-change
rather than $watch
as you already know the place where it gets changed.
It is generally good practice not to fill rootScope
with unnecessary objects, but if you are watching for some variable which is used in entire application such as current user's attribute, I guess it would make sense to put $watch
expression into $rootScope
.
来源:https://stackoverflow.com/questions/26274186/best-practice-in-keeping-watch-functions-away-from-your-controllers