Wednesday, February 18, 2015

Angularjs - Scope

"在 AnuglarJS 里子 Scope 确实会继承父 Scope 中的对象,但当你试下对基本数据类型(string, number, boolean)的 双向数据绑定 时,就会发现一些奇怪的行为,继承并不像你想象的那样工作。子 Scope 的属性隐藏(覆盖)了父 Scope 中的同名属性,对子 Scope 属性(表单元素)的更改并不更新父 Scope 属性的值。这个行为实际上不是 AngularJS 特有的,JavaScript 本身的原型链就是这样工作的。开发者通常都没有意识到 ng-repeat, ng-switch, ng-view 和 ng-include 统统都创建了他们新的子 scopes,所以在用到这些 directive 时也经常出问题"

app.controller('ParentController', function($scope){
 $scope.parentPrimitive = "some primitive"
 $scope.parentObj={};
 $scope.parentObj.parentProperty="some value";
});

app.controller('ChildController', function($scope){
$scope.parentPrimitive="this will not modify the parent";
$scope.parentObj.parentProperty="this will modify the parent"; 
});

如果想使用原型数据:
1. 在子scope种使用$parent.parentPrimitive -- 阻止子Scope创建属性
2. 在父scope中定义函数,让子scope调用

四种scope:
  1. 普通进行原型继承的 Scope —— ng-include, ng-switch, ng-controller, directive with scope: true
  2. 普通原型继承的 Scope 但拷贝赋值 —— ng-repeat。 每个 ng-repeat 的循环都创建新的子 Scope,并且子 Scope 总是获得新的属性。
  3. 独立的 isolate scope —— directive with scope: {...}。它不是原型继承,但 ‘=’, ‘@’ 和 ‘&’ 提供了访问父 Scope 属性的机制。
  4. transcluded scope —— directive with transclude: true。它也遵循原型继承,但它同时是任何 isolate scope 的兄弟。
Details in: http://www.lovelucy.info/understanding-scopes-in-angularjs.html


No comments:

Post a Comment