angularJs自定义指令的三种绑定策略

13 篇文章 0 订阅

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":"251813997@qq.com"}});
				}

			}
		};
	});


 运行结果图片如下:


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值