AngularJS自定义指令标签

创建一个模块

var app = angular.module('app', []);

创建一个简单指令标签

app.directive('alert', function(){
   return {
	template: '<div class="alert">' +
		     '<span class="alert-topic">' +
		        'something went wrong!' +
		     '</span>' +
		     '<span class="alert-description">' +
		        'You must inform the plate and the color of the car!' +
		     '</span>' +
		   '</div>'
   };
});

 使用templateUrl,创建指令标签

app.directive('alert', function(){
	return {
		templateUrl: 'template/alert.html'
	};
});

template目录下alert.html代码如下:

<div class="alert">
	<span class="alert-topic">
		Something went wrong!
	</span>
	<span class="alert-description">
		You must inform the plate and the color of the car!
	</span>	
</div>

    replace属性,控制是否替换原来的标签元素: true/false

 

    restrict属性,声明指令标签以何种方式出现在HTML标签中。


如下示例:

<!DOCTYPE html>
<html ng-app="app">
	<head>
		<meta charset="utf-8">
		<title>Demo</title>
	</head>
	<body>
		<alert></alert>
		<script src="js/angular/angular.min.js"></script>
		<script>
			var app = angular.module('app', []);
			app.directive('alert', function(){
				return {
					templateUrl: 'template/alert.html',
					replace: true,
					restrict: 'E'
				};
			});
		</script>
	</body>
</html>

可以同时使用‘AECM’中的多个或全部。

 scope属性



    前面将自定义指令标签的内容通过硬编码的形式直接写在模板里,这种方式有其局限性。

 

    而通过scope属性,可以将指令标签显示的内容与模板分离,然后通过绑定的方式将其关联起来。如下:

    (1)JS部分:

var app = angular.module('app', []);
app.directive('alert', function(){
 	return {
		templateUrl: 'template/alert.html',
		replace: true,
		restrict: 'E',
		scope: {
			topic: '@topic',
			description: '@description'
		}
	};
});

    (2)alert.html模板部分

<div class="alert">
	<span class="alert-topic">
		<span ng-bind="topic"></span>
	</span>
	<span class="alert-description">
		<span ng-bind="description"></span>
	</span>	
</div>

    (3)在页面中使用该标签实例:

<alert topic="Action!" description="You must inform the plate and the color of the car!"></alert>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值