angularJs自定義指令的三種繫結策略
阿新 • • 發佈:2019-01-07
angularJs中指令scope隔離域中有3種繫結策略:
.directive("test",function(){
return {
scope:{
title:"@",
name:"=",
changeName:"&"
}
}
})
出現了scope就表示這個指令的scope是獨立的,但如果要與外界聯絡,就要使用繫結策略
使用@符號可將本地作用域的變數與DOMHTML程式碼
JS程式碼(run.js)<!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":" [email protected]"}});
}
}
};
});
執行結果圖片如下: