Directive 中的scope
在angularjs 启动的时候,会自动创建一个rootScope 对象。 创建controller和directive 的时候,会自动创建自己的私有scope对象,私有scope从rootScope继承.所有的directives 都有自己的 scope 对象。 在默认的情况下,directive 不会创建他们自己的scope. 他们会用他们父对象的scope作为自己的scope. 但是 angularjs 允许改变这种默认行为。
一、Directive scope 取值不同的区别
1、scope : false (Directives 将使用parent 的scope), 这个是默认值。
假如controller中 $scope.name = “name”;
directive 使用了其parent 的scope 对象作为自己的scope对象。当在controller 中 改变name 对象的值时,directive 的name 会更新, 反之在directive 中更新name 属性,controller 里面的name 也会更新。 因为他们其实是一个对象。
2、scope : true(Directives 会创建一个新的scope,但是创建的这个scope 将从parent controller 中的 scope 对象继承。
directive 里面的name变 controller 中的name 同时改变,controller 中的name变化 directive 里面的name是不变的
3、Scope : {}(Directives 会创建一个新的隔离scope,这个隔离的scope 不从parent scope对象继承)。
这样就避免的directive 中的对象和parent 的对象相互影响,但是由于创建的新的隔离对象是个全新的空对象,因为为这个对象赋值就变成了一个问题。可以通过以下三种方式解决。
restrict: "EA",
scope: {
name: "@",
title: "=",
changeName: "&"
},
template: [
"<div class='line'>",
"Title : <strong>{{title}}</strong>;<br/>Name : <strong>{{name}}</strong>; Change name:<input type='text' ng-model='name' /><br/>",
"</div><div class='line'>",
"<br/><input type='button' ng-click='changeName()' value='Change Name'/>"
].join("")
};
<div class="directive" my-directive
name="{{name}}"
title="title"
change-name="changeName()"
></div>
(1)、通过 @ 传值 (字符串绑定,one way binding(单向绑定),就是传递字符串到directive 进行显示),在调用directive 的时候,需要对 attribute 使用 {{}} 进行传值。
(2)、通过 = 传值 (模型 绑定, two way bingding(双向绑定)) 在调用directive 的时候,需要对 attribute 使用 模型名称 进行传值。
(3)、通过 & 传值 (方法绑定)