今天看了一天angular, 渐渐有点起色了。
github wiki的文档没想到如此清楚 讲的是scope如何用
https://github.com/angular/angular.js/wiki/Understanding-Scopes
基本上scope跟DOM一样有inheritance. childscope能访问parentscope.
当我们用ng-model实现双向绑定的时候,会有特别情况,即不能更改model里面的scope
简单来说,当你使用ng-include , ng-repeat, ng-view,ng-swith等操作时候,会生成一个childscope(比如在每个iteration里毫不知情地), 这时候view->model会创建在已经生成的childscope里面导致不能实现双向绑定。
解决方式有三种,
1.always use ‘.‘ in the model
2. use $.parent in the 'ng-model'
3. define a function in the $parent.scope :
// in the parent scope
$scope.setMyPrimitive = function(value) {
$scope.myPrimitive = value;
}
另外scope 里面, '@someprop' 是单向绑定,’=someprop‘是双向绑定。s
<my-directive interpolated="{{parentProp1}}" twowayBinding="parentProp2">
and
scope: { interpolatedProp: '@interpolated', twowayBindingProp: '=twowayBinding' }
在不考虑isolated scope的情况下,
scope: { interpolatedProp: '@parentProp1',
twowayBindingProp: '=parentProp2' }
parentProp1改变导致interpolatedProp改变,反之不成立。