angular指令中scope的绑定策略

angular指令中scope的绑定策略

scope的作用是让父与子的scope可以进行传递数据,它的绑定一般分为三种情况:
@ :把当前属性作为字符串传递,还可以绑定来自外层scope上的值,在属性中插入{{}}即可;
=: 与父scope中的属性进行双向绑定;
&:传递一个来自父scope中的函数,稍后调用。
'@' 的使用
<person name="{{zhangsan}}"></person>
<person name="{{lisi}}"></person>

 js部分:
var app = angular.module('app',[]);
app.controller('apCtrl',['$scope',function($scope){
	$scope.zhangsan = '张三';
	$scope.lisi = '李四';
	$scope.greet = function(name,word){
		console.log(name +'----'+word)
	};
}])
app.directive('person',function(){
	return {
		replace: true,
		scope: {
			nameself:'@name' //此处的name是<person name="{{lisi}}"></person>的name,也就是{{lisi}}
		},
		restrict:'E',
		template:'<div>姓名:{{nameself}} <input type="text" ng-model="nameself"></div>'
	}
})
'=' 的使用
    {{zhangsan}}
{{lisi}}
<person name="zhangsan"></person>
<person name="lisi"></person>

js部分:
var app = angular.module('app',[]);

app.controller('apCtrl',['$scope',function($scope){
	$scope.zhangsan = '张三';
	$scope.lisi = '李四';
	$scope.greet = function(name,word){
		console.log(name +'----'+word)
	};
}])

app.directive('person',function(){
	return {
		replace: true,
		scope: {
			nameself:'=name' //此处的name父scope下的属性,实现双向绑定,子变父也变
		},
		restrict:'E',
		template:'<div>姓名:{{nameself}} <input type="text" ng-model="nameself"></div>'
	}
})
'&' 的使用
{{zhangsan}}
{{lisi}}
<person name="zhangsan" greet="greet(name,word)"></person>
<person name="lisi" greet="greet(name,word)"></person>
var app = angular.module('app',[]);

app.controller('apCtrl',['$scope',function($scope){
	$scope.zhangsan = '张三';
	$scope.lisi = '李四';
	$scope.greet = function(name,word){
		console.log(name +'----'+word)
	};
}])

app.directive('person',function(){
	return {
		replace: true,
		scope: {
			nameself:'=name',
			greetself:'&greet'
		},
		restrict:'E',
		template:'<div>姓名:{{nameself}} <input type="text" ng-model="word"><div ng-click="greetself({name: nameself,word:word})">click</div></div>'
	}
})
原文地址:https://www.cnblogs.com/rainbow8590/p/7360156.html