问题描述
例如,我试图找到一些关于将 $watch
函数从控制器移动到工厂的最佳实践的好例子.
I tried to find some good examples on best practice in moving $watch
functions from a controller to a factory, for example.
我发现实际上对于最好的做法并没有一致的意见.我见过将 $rootScope
注入工厂并$watch
在那里进行值更改的示例.
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.
另一个建议是尽可能避免它们,并在元素本身上使用 ngChange
代替,例如:
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>
你建议的方式是什么?自从我开始学习 AngularJS 以来,我一直将 $watch
es 放在我的控制器中,但现在我想采用最佳实践方法,尝试使我的控制器尽可能薄.
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.
推荐答案
我想将 $watch
放在哪里很大程度上取决于用例场景.最重要的是要小心 $watch
是不要在 handle 函数内部做任何艰苦的工作,特别是如果你正在观察的东西发生了很大的变化;这会严重影响你的表现.并确保在您的句柄函数中您不会更改已经被监视的其他内容,因为这会导致一系列更改更新.
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.
如果你确定你正在观察的变量只能从一个地方改变,最好使用 ng-change
而不是 $watch
作为你已经知道它被改变的地方.
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.
通常最好不要用不必要的对象填充 rootScope
,但是如果您正在监视整个应用程序中使用的某些变量,例如当前用户的属性,我想这样做是有意义的将 $watch
表达式放入 $rootScope
.
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
.
这篇关于使 `$watch` 函数远离控制器的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!