深入探究AngularJS框架中Scope对象的超级教程(4)

注意:在 link 函数中使用 attrs.$observe('attr_name', function(value) { ... } 来获取独立 Scope 用 ‘@' 符号替换的属性值。例如,在 link 函数中有 attrs.$observe('interpolated', function(value) { ... } 值将被设为 11. (scope.interpolatedProp 在 link 函数中是 undefined,相反scope.twowayBindingProp 在 link 函数中定义了,因为用了 ‘=' 符号)
transclude: true – 这时 directive 创建了一个新的 “transcluded” 子 scope,同时继承父 scope。所以如果模板片段中的内容(例如那些将要替代 ng-transclude 的内容)要求对父 Scope 的基本类型数据进行双向绑定,使用 $parent,或者将 model 一个对象的属性,防止子 Scope 属性覆盖父 Scope 属性。

transcluded 和独立 scope (如果有)是兄弟关系,每个 Scope 的 $parent 指向同一个父 Scope。当模板中的 scope 和独立 Scope 同时存在,独立 Scope 属性 $$nextSibling 将会指向模板中的 Scope。
在下图中,假设 directive 和上个图一样,只是多了 transclude: true

201614151536198.png (640×226)

查看 在线 DEMO,例子里有一个 showScope() 函数可以用来检查独立 Scope 和它关联的 transcluded scope。
总结
一共有四种 Scope:

普通进行原型继承的 Scope —— ng-include, ng-switch, ng-controller, directive with scope: true
普通原型继承的 Scope 但拷贝赋值 —— ng-repeat。 每个 ng-repeat 的循环都创建新的子 Scope,并且子 Scope 总是获得新的属性。
独立的 isolate scope —— directive with scope: {...}。它不是原型继承,但 ‘=', ‘@' 和 ‘&' 提供了访问父 Scope 属性的机制。
transcluded scope —— directive with transclude: true。它也遵循原型继承,但它同时是任何 isolate scope 的兄弟。
对于所有的 Scope,Angular 总是会通过 Scope 的 $parent, $$childHead 和 $$childTail 属性记录父-子关系。

PS:scope和rootscope的区别
scope是html和单个controller之间的桥梁,数据绑定就靠他了。rootscope是各个controller中scope的桥梁。用rootscope定义的值,可以在各个controller中使用。下面用实例详细的说明一下。
1,js代码

phonecatApp.controller('TestCtrl',['$scope','$rootScope', function($scope,$rootScope) { $rootScope.name = 'this is test'; } ]); phonecatApp.controller('Test111Ctrl',['$scope','$rootScope', function($scope,$rootScope) { $scope.name = $rootScope.name; } ]);

2,html代码

<div ng-controller="TestCtrl"> I set the global variable.<strong>{{$root.name}}</strong> </div> <div ng-controller="Test111Ctrl"> 1,get global variable .<strong>{{name}}</strong><br> 2,get global variable .<strong>{{$root.name}}</strong> </div>

3,显示结果

I set the global variable.this is test 1,get global variable .this is test 2,get global variable .this is test

由结果可以看出来,$rootScope.name设置的变量,在所有controller里面都是可以直接用{{$root.name}}来显示的,很强大。那当然也可以赋值给scope.
 

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgwxwj.html