AngularJS:$observe 和 $watch 方法的区别 [英] AngularJS : Difference between the $observe and $watch methods

查看:19
本文介绍了AngularJS:$observe 和 $watch 方法的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 WatchersObservers 都会在 $scope 中的某些内容在 AngularJS 中发生变化时立即计算.但无法理解两者之间究竟有什么区别.

我最初的理解是,Observers 是为角度表达式计算的,角度表达式是 HTML 端的条件,其中 Watchers$scope.$watch() 时执行 函数被执行.我的想法正确吗?

解决方案

$observe()Attributes 对象上的一个方法,因此,它只能用于观察/观察 DOM 属性的值变化.它仅在指令内部使用/调用.当您需要观察/观察包含插值(即 {{}} 的 DOM 属性)的 DOM 属性时,请使用 $observe.
例如,attr1="Name: {{name}}",然后在指令中:attrs.$observe('attr1', ...).
(如果你尝试 scope.$watch(attrs.attr1, ...) 它不会工作,因为 {{}} s - 你会得到 undefined.)使用 $watch 处理其他所有事情.

$watch() 更复杂.它可以观察/观察表达式",其中表达式可以是函数或字符串.如果表达式是字符串,则它是 $parse'd(即,评估为 Angular 表达式) 到一个函数中.(正是这个函数在每个摘要循环中被调用.)字符串表达式不能包含 {{}}.$watch 是 Scope 对象上的一个方法,因此它可以在您有权访问的任何地方使用/调用到范围对象,因此在

  • 控制器 -- 任何控制器 -- 通过 ng-view、ng-controller 或指令控制器创建的控制器
  • 指令中的链接函数,因为它也可以访问范围

因为字符串被评估为 Angular 表达式,所以当你想要观察/观察模型/范围属性时,经常使用 $watch.例如,attr1="myModel.some_prop",然后在控制器或链接函数中:scope.$watch('myModel.some_prop', ...)scope.$watch(attrs.attr1, ...)(或 scope.$watch(attrs['attr1'], ...)).
(如果您尝试attrs.$observe('attr1'),您将得到字符串myModel.some_prop,这可能不是您想要的.)

正如在对@PrimosK 的回答的评论中所讨论的,所有 $observes 和 $watches 都会在每个摘要周期进行检查.>

具有隔离作用域的指令更复杂.如果使用 '@' 语法,您可以 $observe 或 $watch 包含插值(即 {{}} 的)的 DOM 属性.(它与 $watch 一起工作的原因是因为 '@' 语法为我们做了 interpolation,因此 $watch 看到一个没有 {{}} 的字符串.)为了更容易记住什么时候使用哪个,我建议在这种情况下也使用 $observe.

为了帮助测试所有这些,我编写了一个 Plunker,它定义了两个指令.一个 (d1) 不创建新作用域,另一个 (d2) 创建一个隔离作用域.每个指令具有相同的六个属性.每个属性都是 $observe'd 和 $watch'ed.

<div d1 attr1="{{prop1}}-test" attr2="prop2" attr3="33" attr4="'a_string'"attr5="a_string" attr6="{{1+aNumber}}"></div>

查看控制台日志,可以看到 $observe 和 $watch 在链接功能上的区别.然后点击链接,查看点击处理程序所做的属性更改触发了哪些 $observe 和 $watches.

请注意,当链接函数运行时,尚未评估任何包含 {{}} 的属性(因此,如果您尝试检查这些属性,则会得到 undefined).查看内插值的唯一方法是使用 $observe(如果使用带有@"的隔离范围,则使用 $watch).因此,获取这些属性的值是一个异步操作.(这就是我们需要 $observe 和 $watch 函数的原因.)

有时您不需要 $observe 或 $watch.例如,如果您的属性包含数字或布尔值(不是字符串),只需评估一次:attr1="22",然后在您的链接函数中:var count =范围.$eval(attrs.attr1).如果它只是一个常量字符串 –attr1="我的字符串" –然后只需在您的指令中使用 attrs.attr1(不需要 $eval()).

另请参阅Vojta 的谷歌群组帖子,了解 $watch 表达式.

I know that both Watchers and Observers are computed as soon as something in $scope changes in AngularJS. But couldn't understand what exactly is the difference between the two.

My initial understanding is that Observers are computed for angular expressions which are conditions on the HTML side where as Watchers executed when $scope.$watch() function is executed. Am I thinking properly?

解决方案

$observe() is a method on the Attributes object, and as such, it can only be used to observe/watch the value change of a DOM attribute. It is only used/called inside directives. Use $observe when you need to observe/watch a DOM attribute that contains interpolation (i.e., {{}}'s).
E.g., attr1="Name: {{name}}", then in a directive: attrs.$observe('attr1', ...).
(If you try scope.$watch(attrs.attr1, ...) it won't work because of the {{}}s -- you'll get undefined.) Use $watch for everything else.

$watch() is more complicated. It can observe/watch an "expression", where the expression can be either a function or a string. If the expression is a string, it is $parse'd (i.e., evaluated as an Angular expression) into a function. (It is this function that is called every digest cycle.) The string expression can not contain {{}}'s. $watch is a method on the Scope object, so it can be used/called wherever you have access to a scope object, hence in

  • a controller -- any controller -- one created via ng-view, ng-controller, or a directive controller
  • a linking function in a directive, since this has access to a scope as well

Because strings are evaluated as Angular expressions, $watch is often used when you want to observe/watch a model/scope property. E.g., attr1="myModel.some_prop", then in a controller or link function: scope.$watch('myModel.some_prop', ...) or scope.$watch(attrs.attr1, ...) (or scope.$watch(attrs['attr1'], ...)).
(If you try attrs.$observe('attr1') you'll get the string myModel.some_prop, which is probably not what you want.)

As discussed in comments on @PrimosK's answer, all $observes and $watches are checked every digest cycle.

Directives with isolate scopes are more complicated. If the '@' syntax is used, you can $observe or $watch a DOM attribute that contains interpolation (i.e., {{}}'s). (The reason it works with $watch is because the '@' syntax does the interpolation for us, hence $watch sees a string without {{}}'s.) To make it easier to remember which to use when, I suggest using $observe for this case also.

To help test all of this, I wrote a Plunker that defines two directives. One (d1) does not create a new scope, the other (d2) creates an isolate scope. Each directive has the same six attributes. Each attribute is both $observe'd and $watch'ed.

<div d1 attr1="{{prop1}}-test" attr2="prop2" attr3="33" attr4="'a_string'"
        attr5="a_string" attr6="{{1+aNumber}}"></div>

Look at the console log to see the differences between $observe and $watch in the linking function. Then click the link and see which $observes and $watches are triggered by the property changes made by the click handler.

Notice that when the link function runs, any attributes that contain {{}}'s are not evaluated yet (so if you try to examine the attributes, you'll get undefined). The only way to see the interpolated values is to use $observe (or $watch if using an isolate scope with '@'). Therefore, getting the values of these attributes is an asynchronous operation. (And this is why we need the $observe and $watch functions.)

Sometimes you don't need $observe or $watch. E.g., if your attribute contains a number or a boolean (not a string), just evaluate it once: attr1="22", then in, say, your linking function: var count = scope.$eval(attrs.attr1). If it is just a constant string – attr1="my string" – then just use attrs.attr1 in your directive (no need for $eval()).

See also Vojta's google group post about $watch expressions.

这篇关于AngularJS:$observe 和 $watch 方法的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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