ITeye博客

AngularJS自定义指令标签

2008winstar · 2014-11-03 22:00 · angular · Web前端 · Markdown

创建一个模块

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)

暂无评论。

评论功能维护中,当前仅展示历史评论。