javascript - AngularJS 范围 $id 的值是如何设置的?似乎没有增量。

标签 javascript angularjs angularjs-scope

我正在尝试进一步研究 AngularJS 中的范围层次结构。最近,我一直在密切关注 scope.$id 编号——我注意到应用于范围的 $id 的值并不是以增量方式应用的。例如:

<html ng-app="app">
    <body ng-controller="appCtrl">
         <!-- ngInclude: 'notifications.tpl.html' -->
         <!-- ngInclude: 'otherTpl.tpl.html' -->
          <div ng-include="someView.tpl.html">
          <ui-view></ui-view>
     </body>
</html>

这棵树反射(reflect)了我的 DOM,其中 html 元素的范围 $id 为 1,body 有一个 $id 为 2,ng-include 的范围 $id 为 6,这似乎没有多大顺序意义。

这些 id 号码是如何确定的?这有关系吗?

谢谢!

最佳答案

id算法为:

function HashMap(array, isolatedUid) {
  if (isolatedUid) {
    /* Initialize uid to zero for the rootscope */
    var uid = 0;
    this.nextUid = function() {
      return ++uid;
    /* Increment the id */
    };
  }
  forEach(array, this.put, this);
}

范围算法是:

        if (isolate) {
          child = new Scope();
          /* Increment when a directive which uses isolate scope is created */
          child.$root = this.$root;
        } else {
          // Only create a child scope class if somebody asks for one,
          // but cache it to allow the VM to optimize lookups.
          if (!this.$$ChildScope) {
            this.$$ChildScope = createChildScopeClass(this);
          }
          /* Increment when a directive which uses child scope is created */
          child = new this.$$ChildScope();
        }

If you find that your code is now throwing a $compile:multidir error, check that you do not have directives on the same element that are trying to request both an isolate and a non-isolate scope and fix your code.

If your code depends on this behavior (non-isolate directive needs to access state from within the isolate scope), change the isolate directive to use scope locals to pass these explicitly.

scope.$new() takes one argument - a boolean indicating if the newly-created child scope should be isolated (not prototypically inheriting from the current scope). Previously the first argument was reference to the controller constructor, but because of the scope/controller separation the controllers should be instantiated via the $controller service.

引用资料

关于javascript - AngularJS 范围 $id 的值是如何设置的?似乎没有增量。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30434493/

相关文章:

javascript - 清除 ionic 搜索栏中的文本

javascript - AngularJS 分页 - id 计数器在新页面中从 1 开始

javascript - 嵌套 ng-repeat 在父重复 ID 上重复

javascript - 如何在 Angular js文件中使用cookie?

javascript - 防止 JQGrid 在请求失败后恢复行

javascript - TweenMax - 如何以不同的速度对元素进行动画处理?

javascript - 如果复选框被选中,如何知道将元素添加到数组中,如果未选中,如何将其删除?

angularjs - 如何在 ng-repeat 中动态更新 ng-model?

javascript - Angularjs - 指令 Controller 加载速度比应用程序 Controller 快 - 值未定义

javascript - 在 translateX 后将跨度元素居中对齐