2

I am trying to further investigate the scope hierarchy in AngularJS. Recently, I've been paying close attention to the scope.$id numbering—and I've noticed that the value applied to a scope's $id isn't applied in an incremental manner. For example:

<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>

This tree mirrors that of my DOM, where the html element has a scope $id of 1, body has an $id of 2, and the ng-include has a scope $id of 6, which doesn't seem to make much sense sequentially.

How are these id numbers determined? Does it matter at all?

Thanks!

1 Answer 1

1

The id algorithm is:

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);
}

The scope algorithm is:

        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.

References

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.