XIANFESchool / FE-problem-collection

前端问题收集和知识经验总结
https://github.com/ShuyunXIANFESchool/FE-problem-collection/issues
63 stars 22 forks source link

AngularJS 1.x 中的 scope #7

Open hjzheng opened 8 years ago

hjzheng commented 8 years ago

关于 AngularJS 1.x 中的 scope, 官方 guide 已经讲的很清楚了,大家自己阅读就行。

官方 guide (中文): http://docs.ngnice.com/guide/scope 官方 guide (英文): https://docs.angularjs.org/guide/scope

我在这里只强调几个 scope 技巧:

document.querySelectorAll('.ng-scope').forEach(function(node) {
    node.style.border = '1px solid red';
});

技巧1: 查看 dom 元素 上的 scope, 更多技巧,请参看 https://github.com/hjzheng/CUF_meeting_knowledge_share/issues/40

angular.element($0).scope();
  • 父 scope 和 子 scope 存在继承关系(这里实际上利用的是 JS 的原型继承, 请翻看 AngularJS 源码 关于scope中的 $new 方法),所以在父子 scope 中定义同名的变量,此时,你需要使用父元素上定义的变量,需要额外注意,防止被子 scope 的同名变量覆盖掉, 当然,现在都使用 controllerAs 的方式。
  • 额外关注一些指令,因为它们会产生子的 scope, 例如 ngController, ngInclude, ngRepeat 等,相应的说明都可以参看官方 API, 因为上面有详细的说明
  • scope 提供了$watch, $watchGroup, $watchCollection, 注意三者的区别, 并灵活运用
  • scope 提供事件机制. 事件优化 请参考 https://segmentfault.com/a/1190000000502981#articleHeader12
  • $emit
  • $broadcast
  • $on

技巧2:慎用事件传播,先用其他方式,使用双向数据绑定或共享service等方法来代替。 $on 和 $broadcast 的源码解读 $on 将注册的函数放入 scope 对象的 $$listeners 中。 $broadcast 对 scope 树进行的遍历(深度优先遍历),然后在 $$listeners 上找到注册的方法后,执 行,效率不高

  • scope 的 $apply 和 $digest $apply 会使 ng 进入 $digest cycle, 并从 $rootScope 开始遍历(深度优先)检查数据变更。 $digest 仅会检查该 scope 和它的子 scope,当你确定当前操作仅影响它们时,用 $digest 可以稍微提升性能。
  • scope 与 指令 https://github.com/hjzheng/angular-directive-learning#lesson-3

通过设置 scope 的值 ,false 使用父 scope, true 产生一个子 scope 继承自父scope, {} 隔离scope