angular指令中@,=,&的区别

当directive中的scope设置为一个对象的时候,该指令就有了一个独立的作用域,AngularJS提供了一种绑定策略用于隔离作用域和外部作用域进行通信。

1、@(or @attr)

使用@符号可以进行单项的数据绑定,取值总是一个字符串,所以要用{{}}。

另外这也是一个单向的绑定,外部数据改变会反应到内部,但是内部数据变数据变化,外部不会变。

属性要用-连接,scope中写它的驼峰格式。

如果没有通过@attr指定属性名称,那么本地名称要与DOM属性的名称一致。

<!DOCTYPE html>
<html ng-app="myApp">
<head>
	<meta charset="utf-8">
	<title>AngularJS</title>
</head>
<body>
	<div ng-controller="parent">
		<div>
			<input type="text" ng-model="name"/>
		</div>
		<my-name show-name="{{name}}">
		
		</my-name>
	</div>
</body>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript">
	var app = angular.module("myApp", []);
	app.controller("parent", function($scope){
		$scope.name = "Jhon";
	}).directive("myName", function(){
		return {
			restrict:"EA",
			scope:{
				showName: '@'
				// name: '@showName'
			},
			template:'<input type="text" ng-model="showName"/>',
			// template:'<input type="text" ng-model="name"/>',
		}
	});
</script>
</html>


2、= (or =attr)

使用=进行双向数据绑定,任何一方的值改变都会反应到另一方。因为是双向绑定,所以不要使用{{}},不然以下demo会报错。

属性要用-连接,scope中写它的驼峰格式。

如果没有通过@attr指定属性名称,那么本地名称要与DOM属性的名称一致。

<!DOCTYPE html>
<html ng-app="myApp">
<head>
	<meta charset="utf-8">
	<title>AngularJS</title>
</head>
<body>
	<div ng-controller="parent">
		<div>
			<input type="text" ng-model="name"/>
		</div>
		<my-name show-name="name">
		
		</my-name>
	</div>
</body>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript">
	var app = angular.module("myApp", []);
	app.controller("parent", function($scope){
		$scope.name = "Jhon";
	}).directive("myName", function(){
		return {
			restrict:"EA",
			scope:{
				showName: '='
			},
			template:'<input type="text" ng-model="showName"/>'
		}
	});
</script>
</html>


3、&(or &attr)

&用来绑定外部的函数。

属性要用-连接,scope中写它的驼峰格式。

如果没有通过@attr指定属性名称,那么本地名称要与DOM属性的名称一致。

<!DOCTYPE html>
<html ng-app="myApp">
<head>
	<meta charset="utf-8">
	<title>AngularJS</title>
</head>
<body>
	<div ng-controller="parent">
		<div>
			<input type="text" ng-model="count"/>
		</div>
		<my-name show-name="increment()">
		
		</my-name>
	</div>
</body>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript">
	var app = angular.module("myApp", []);
	app.controller("parent", function($scope){
		$scope.count = 0;
		$scope.increment = function(){
			$scope.count++;
		};
	}).directive("myName", function(){
		return {
			restrict:"EA",
			scope:{
				showName: '&'
			},
			template:'<input type="button" ng-click="showName()" value="+1"/>'
		}
	});
</script>
</html>





  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值