您的位置:首页 > Web前端 > AngularJS

angularjs的自定义directive指令的绑定策略scope:”@”、”=”、”&”

2016-08-24 14:15 555 查看
通常我们知道指令默认是可以跟外界通信的.

比如:

<div
ng-controller=
"mytest"
>
<test></test>
</div>
test自定义指令是可以访问到mytest控制器的scope

要想把test自定义指令独立作用域,也就是说跟mytest切断关系:可以加上指令的参数scope:{},这样就能做到互不相干了

但是也不可能完成切断关系,总会有某些东西要互相交互,如果想跟mytest控制器的某个scope属性交互,就要用绑定策略

下面来介绍三种绑定策略的做法

1.@符号

“@”是通过DOM的属性来跟mytest控制器交互绑定一起

<div
ng-controller=
"mytest"
>
<test></test>
</div>
app.controller(
"mytest"
,
function
($scope)
{
$scope.name
=
"jack"
;
$scope.age
= 25;
});
app.directive(
"test"
,
function
(){
return
{
restrict
:
"E"
,
template
:
'<div
name="{{name}}"></div>'
,
replace
:
true
,
scope
: {
name
:
"@"
},
controller
:
function
($scope){
console.log($scope.name);
//"jack"
console.log($scope.age);
//age是undefined,因为没有跟mytest进行交互
},
link
:
function
($scope)
{
console.log($scope.name);
//"jack"
console.log($scope.age);
//age是undefined,因为没有跟mytest进行交互
}
}
});
重点:

scope : {

name : “@”

}

scope对象声明了一个属性name,然后在DOM元素的属性加上一个name,(注意两边的名字必须要一致)这样就可以进行交互操作

2.=符号

“=”有双重绑定的功能,比如mytest控制器与test子指令进行双重绑定(单个字符串、对象都是有效的)下面代码用对象来演示

<div
ng-controller=
"mytest"
>
父:<input
type=
"text"
ng-model=
"data.name"
/>
<test></test>
</div>
app.controller(
"mytest"
,
function
($scope)
{
$scope.data
= {
name
:
"jack"
,
age
: 25
}
});
app.directive(
"test"
,
function
(){
return
{
restrict
:
"E"
,
template
:
'<div
data="data">子指令:<input ng-model="data.name" /></div>'
,
replace
:
true
,
scope
: {
data
:
"="
},
controller
:
function
($scope){
console.log($scope.data);
//Object
{name: "jack",age: 25}
},
link
:
function
($scope)
{
console.log($scope.data);
//Object
{name: "jack",age: 25}
}
}
});
3.&符号

“&”的意思是子指令能调用父控制器的方法,这里的指令template元素点击调用控制器的getName方法

<div
ng-controller=
"mytest"
>
<test></test>
</div>
app.controller(
"mytest"
,
function
($scope)
{
$scope.getName
=
function
(){
console.log(
"jack"
);
}
});
app.directive(
"test"
,
function
(){
return
{
restrict
:
"E"
,
template
:
'<div
get-name="getName()">子指令:<a href="javascript:void(0)" ng-click="getName()">点击调用父方法</a></div>'
,
replace
:
true
,
scope
: {
getName
:
"&"
},
controller
:
function
($scope){
$scope.getName();
//"jack"
},
link
:
function
($scope)
{
$scope.getName();
//"jack"
}
}
});
源引:
http://raowensheng.com/2014/05/08/angularjs%E7%9A%84%E8%87%AA%E5%AE%9A%E4%B9%89directive%E6%8C%87%E4%BB%A4%E7%9A%84%E7%BB%91%E5%AE%9A%E7%AD%96%E7%95%A5scope%E3%80%81%E3%80%81/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  angularjs directive scope