我正在尝试进一步研究 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/