1. 程式人生 > >angularJs自定義指令的三種繫結策略

angularJs自定義指令的三種繫結策略

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>
JS程式碼(run.js)
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]
"}}); } } }; });
 執行結果圖片如下: