前端之家收集整理的这篇文章主要介绍了
AngularJS 指令中的属性的绑定方式,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
angularjs 指令的属性绑定方式有三种表示方式:@,=,&
@H_
301_4@
1:先说指令域scope的@
@H_
301_4@ 我觉得描述很费劲,直接用
代码来阐述:
<!doctypehtml>
<htmlng-app='myApp'>
<head>
</head>
<body>
<divng-controller="listCtrl">
<inputtype="text"ng-model="t"/>
<kidtitle="{{t}}">//这个必须指定的,这里的title是指令里scope的@对应的,t就是控制域scope下的
<span>我的angularjs</span>
</kid>
</div>
<scripttype="text/javascript"src="angular.js"></script>
<scripttype="text/javascript"src="main05.js"></script>
</body></html>
@H_
301_4@main05.js
varmyApp=angular.module('myApp',[]);
myApp.controller('listCtrl',function($scope){
$scope.logchore="motorola";
});
myApp.directive('kid',function(){
return{
'restrict':'E',scope:{
title:"@"
},template:'<div>{{title}}</div>'
}
});
在输入框输入数字会绑定到指令模板的title中。
@H_
301_4@
2:再说说Scope的 =
<!doctypehtml>
<htmlng-app='myApp'>
<head>
</head>
<body>
<divng-controller="listCtrl">
<inputtype="text"ng-model="t"/>
<kidtitle="t">//和上面相比,这个直接赋值等于scope域下的t了
<p>{{title}}</p>
<span>我的angularjs</span>
</kid>
</div>
<scripttype="text/javascript"src="angular.js"></script>
<scripttype="text/javascript"src="main05.js"></script>
</body></html>
@H_
301_4@main05.js
代码如下:
varmyApp=angular.module('myApp',scope:{
title:"="
},template:'<div>{{title}}</div>'
}
});
@H_
301_4@
3:最后说&,这个是用来方法调用的
<!doctypehtml>
<htmlng-app='myApp'>
<head>
</head>
<body>
<divng-controller="listCtrl">
<kidflavor="logchore()"></kid>//先比=,函数赋值的形式,而logchore函数必须是域scope下声明的函数
</div>
<scripttype="text/javascript"src="angular.js"></script>
<scripttype="text/javascript"src="main05.js"></script>
</body></html>
@H_
301_4@main05.js
代码如下:
varmyApp=angular.module('myApp',function($scope){
$scope.logchore=function(){
alert('ok');
};
});
myApp.directive('kid',scope:{
flavor:"&"
},template:'<div><buttonng-click="flavor()"></button></div>'
}
});
@H_
301_4@如果logchore带有参数,
<!doctypehtml>
<htmlng-app='myApp'>
<head>
</head>
<body>
<divng-controller="listCtrl">
<kidflavor="logchore(t)"></kid>
</div>
<scripttype="text/javascript"src="angular.js"></script>
<scripttype="text/javascript"src="main05.js"></script>
</body></html>
@H_
301_4@main05.js
代码如下:
varmyApp=angular.module('myApp',function($scope){
$scope.logchore=function(x){
alert(x);
};
});
myApp.directive('kid',template:'<div><inputtype="text"ng-model="v"/><buttonng-click="flavor({t:v})"></button></div>'
}
});