题目形貌:
//app.js
angular.module('deapp', [])
.controller('ParentCtrl', ['$scope', ParentCtrl])
.controller('ChildCtrl', ['$scope', ChildCtrl]);
function ParentCtrl($scope) {
$scope.description = '';
}
function ChildCtrl($scope) {
}
//index.html
<div data-ng-controller="ParentCtrl">
<div data-ng-controller="ChildCtrl">
<textarea class="description" data-ng-model="description"></textarea>
</div>
</div>
我修正textarea的内容时,绑定的description完整没更新,只能用chrome插件ng-inspector看一下。
图1 初始scope
图2 输入后ChildCtrl 涌现description
所以能够看到题目变成了Angular Scope Inheritance
Angular Scope Inheritance
我用word文档画了scope的继续图示,以下
图3 初始scope
图 4 毛病的给ChildCtrl添加了description
在这个图能够看到实际上并没有更新父级scope的description,反而在当前地点的ChildCtrl scope新建了description。也就是说与textarea绑定的model实际上是ChildCtrl scope中的description。
$scope的继续是原型链继续,有两个特性:
读子类的属性时,子类有这个属性(hasOwnProperty)的时刻则读子类本身的,子类没有的时刻读父类的,不论子类有无这个属性,在子类上都不会有新属性被建立。
写子类的属性时,假如子类有这个属性(hasOwnProperty)则写子类的,子类没有的话就会在子类上新建一个同名的新属性,而父类继续过来的属性被隐蔽。
————来自http://pinkyjie.com/2015/02/07/prototypal-inheritance-of-scope-in-angularjs/
所以关于description也是一样,读description时,先在ChildCtrl中读,读不到就到ParentCtrl中读,所以事先给ParentCtrl的description设置的初始值,在页面革新后是能够显现出来的。
然则,写description的时刻就不一样了,在ChildCtrl中找不到就直接建立一个新的属性,父级scope的同名属性就被隐蔽了,textarea绑定的模子也就变成了ChildCtrl scope中的description,今后再怎样修正textarea的内容,父级scope的description永久坚持本来的值。
这不是我想看到的,要领是有的,运用.就可以处理这个题目了。
只需改html,将textarea显现绑定到$parent.description
<div data-ng-controller=”ParentCtrl”>
<form data-ng-controller="ChildCtrl"> <textarea class="description" data-ng-model="$parent.description"></textarea> </form>
</div>
运用对象的情势来绑定description
// app.js
function ParentCtrl($scope) {$scope.info = { description: '156' };
}
function ChildCtrl($scope) {
}// index.html
<div data-ng-controller=”ParentCtrl”><form data-ng-controller="ChildCtrl"> <textarea class="description" data-ng-model="info.description"></textarea> </form>
</div>
为何一个.就可以处理题目了呢,以第二个要领为例。
写的时刻是写info.description,须要先读info,ChildCtrl没有info,因而去ParentCtrl读,找到info后,就写父级scope的info.description。
Angular Scope Inheritance的细致图文说明注解