angularJs中指令scope隔离域中有3种绑定策略:
.directive("test",function(){
return {
scope:{
title:"@",
name:"=",
changeName:"&"
}
}
})
出现了scope就表示这个指令的scope是独立的,但如果要与外界联系,就要使用绑定策略
使用@符号可将本地作用域的变量与DOM属性的值进行绑定,即我们通过@得到title属性的值
使用=符号可将本地作用域上的属性与父级作用域上的属性进行双向绑定,即我们通过=得到name的引用。可以同值传递和引用传递的理解相结合
使用&符号可以对父级作用域进行绑定,以便在其中运行函数,简单说就是绑定函数用的
实例:
HTML代码
<!doctype html>
<html ng-app="myApp">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="lib/angular/angular.js"></script>
<script src="js/run.js"></script>
</head>
<body ng-controller='BodyController'>
<div ng-controller='SomeController'>
{{someBareValue}}
<button ng-click='someAction()'>Communicate to child</button>
<div ng-controller='ChildController'>
{{someBareValue}}
<button ng-click='childAction'>Communicate to parent</button>
</div>
</div>
<input type="text" ng-model='user'/></br>
<div scope-example user-data-name="user" on-send='sendMail(email)' from-name={{name}}></div>
</body>
</html>
angular.module("myApp",[])
.controller("BodyController",function($scope,$timeout,$interval){
$scope.name = "黄小明";
$scope.user = "李四";
var i=0;
var timer = $interval(function(){
i++;
$scope.name = "黄大明";
$scope.user = "李四" + i;
if(i==4){
$interval.cancel(timer);
}
},2000);
$scope.sendMail = function(email){
console.log(email)
alert(email.email)
}
})
.controller("SomeController",function($scope){
$scope.someBareValue = "黄小明";
$scope.someAction = function(){
$scope.someBareValue = "你好呀黄大明";
}
})
.controller("ChildController",function($scope){
$scope.childAction = function(){
$scope.someBareValue = "这是点击controller的孩子";
}
})
.directive("scopeExample",function(){
return {
restrict: "EA",
scope: {
userDataName: "=userDataName",
onSend: "&onSend",
fromName: "@fromName"
},
template: '<div ng-click="test()">Now you should show email fromName={{fromname}}</div></br><input ng-model="userDataName"/></br><p>这是从父级获取到的{{userDataName}}</p>',
link: function(scope, element, attrs) {
// scope.userDataName = {
// name: "李四"+i
// };
scope.fromname = scope.fromName;
scope.test = function(){
scope.onSend({"email":{"email":"251813997@qq.com"}});
}
}
};
});