`
HYFY
  • 浏览: 11500 次
  • 性别: Icon_minigender_1
  • 来自: 河北
文章分类
社区版块
存档分类
最新评论

温故知新:Angular下的 directive

阅读更多
Angularjs directive
Angularjs 提供的directive指令可以用来写自己的命令甚至标签。
用例子来说事吧:自定义指令example

directive.html
<!DOCTYPE html>
<html ng-app='myApp'>
  <head>
    <title>TestDirective</title>
    <link href='css/bootstrap.css' rel='stylesheet' type='text/css' />
    <script lang='javascript' src='lib/js/angular/angular.min.js'></script>
	<script src='js/TestDirectiveController.js' type='text/javascript'></script>
  </head>
  <body>
	<div example></div>
  </body>
</html>


TestDirective.js
angular.module('myApp',[])
	.controller('TestDirectiveController',function($scope){
		$scope.content = {'name':'LiMing','age':'12'};
	})
	.directive('example',function(){
		return {
                        restrict:'A'
			template:'Name:{{content.name}},Age:{{content.age}}';
		}
	});

在这里面定义了名为example的directive,它是一个function,返回值是一个对象:
restrict属性表明example要匹配的的是一个标签('E')还是标签中的一个属性('A'),如这里的html中将example用在了div中,因此example便成了div的一个属性,因此restrict返回的是A;
template属性表明要填充到div中的内容。
打开网页运行后便在此div处显示出Name:LiMing,Age:12.

在强大一点,可以用angular的directive功能实现重复模板的复用。例子如下:
directive.html
<!DOCTYPE html>
<html ng-app='myApp'>
  <head>
    <title>TestDirective</title>
    <link href='css/bootstrap.css' rel='stylesheet' type='text/css' />
    <script lang='javascript' src='lib/js/angular/angular.min.js'></script>
	<script src='js/TestDirectiveController.js' type='text/javascript'></script>
  </head>
  <body>
	<div example info='LiMing'></div>
	<div example info='WangYu'></div>
  </body>
</html>


info.html(要复用的模板)
<div>
	Hello{{peopelInfo.name}},你已经{{peopleInfo.age}}岁了。
</div>


TestDirectiveController.js
angular.module('myApp',[])
	.controller('TestDirectiveController',function($scope){
		$scope.LiMing = {'name':'LiMing','age':'12'};
		$scope.WangYu = {'name':'WangYu','age':'14'};
	})
	.directive('example',function(){
		return {
			restrict:'A',
			scope:{
				peopleInfo:'=info'
			},
			templateUrl:'info.html';
		}
	});

这里scope中的内容表明了模板中的poepleInfo变量要被谁替代,在这里是被info取代,info在directive.html中可以看到分别代表着'LiMing'和'WangYu',这样替代后便绑定到了TestDirectiveController下的$scope对应的变量上。
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics