您的位置:首页 > 运维架构

独立scope及其绑定策略

2017-07-03 23:41 417 查看
1、独立scope

<hello></hello>
<hello></hello>
<hello></hello>


var myModule = angular.module("MyModule", []);
myModule.directive("hello",function(){
return {
restrict:'AE',
scope:{},
template:'<div><input type="text" ng-model="userName"/></div>',
replace:true
}
})


创建独立scope只需要添加一个配置项scope即可。

没有独立scope的时候,任何一个指令的内容发生变化的时候,都会影响到其它实例。添加后每个实例都有自己的独立scope,实例之间互不影响。

scope的绑定策略



<div ng-controller="MyCtrl">
<drink flavor="{{ctrlFlavor}}"></drink>
</div>


var myModule = angular.module("MyModule", []);
myModule.controller('MyCtrl',['$scope',function($scope){
$scope.ctrlFlavor="百威";
}])
myModule.directive('drink',function(){
return {
restrict:'AE',
template:'<div>{{flavor}}</div>',
link:function(scope,element,attrs){
scope.flavor = attrs.flavor;
}
}
})


指令中显示的是控制器中的内容

@绑定

myModule.directive('drink',function(){
return {
restrict:'AE',
scope:{
flavor:'@'
}
template:'<div>{{flavor}}</div>'
//,
//link:function(scope,element,attrs){
//  scope.flavor = attrs.flavor;
//}
}
})


@绑定传递的是字符串

=绑定,双向绑定

myModule.directive('drink',function(){
return {
restrict:'AE',
scope:{
flavor:'@'
}
template:'<input type="text" ng-model="flavor"/>'
}
})


<div ng-controller="MyCtrl">
<input type="text" ng-model="ctrlFlavor">
<drink flavor="ctrlFlavor"></drink>
</div>


&绑定

<div ng-controller="MyCtrl">
<greeting greet="sayHello(name)"></greeting>
<greeting greet="sayHello(name)"></greeting>
<greeting greet="sayHello(name)"></greeting>
</div>


var myModule = angular.module("MyModule", []);
myModule.controller('MyCtrl',['$scope',function($scope){
$scope.sayHello=function(name){
alert("hello"+name);
}
}])
myModule.directive('greeting',function(){
return {
restrict:'AE',
scope:{
greet:'&'
}
template:'<input type="text" ng-model="userName" /><button ng-click="greet({name:userName})"'
}
})


&传递函数,调用父级作用域上的函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: