您的位置:首页 > Web前端 > AngularJS

AngularJS学习笔记(六)---指令

2015-07-29 17:01 661 查看

AngularJS四大核心特性—指令

在之前的内容中提到AngularJS的四个核心的特性是以下四点:

MVC

模块化和依赖注入

双向数据绑定

指令

指令模块

在指令这个模块中主要讲述指令的使用以及原理,内容包括:

解析最简单的指令hello:匹配模式restrict

解析最简单的指令hello:template、templateUrl、$templateCache

解析最简单的指令hello:replace与transclude

comile与link(操作元素、天剑CSS样式、绑定事件)

指令与控制器之间的交互

指令间的交互

scope的类型与独立scope

scope的绑定策略

AngularJS内置的指令

实力解析Expander

实例解析Accordion

指令的运行原理:compile和link

总结:ERP类型的系统必备的UI组件

总结:互联网/电商型系统必备的UI组件

第三方指令库angular-ui

directive思想的起源和原理概述

解析最简单的指令hello

我们首先来看一个实际的例子:

html

<!doctype html>
<html ng-app="MyModule">
<head>
<meta charset="utf-8">
</head>
<body>
<hello></hello>
<div hello></div>
<div class="hello"></div>
<!-- directive:hello -->
<div></div>
</body>
<script src="framework/angular-1.3.0.14/angular.js"></script>
<script src="HelloAngular_Directive.js"></script>
</html>


js

var myModule = angular.module("MyModule", []);
myModule.directive("hello", function() {
return {
restrict: 'AEMC',
template: '<div>Hi everyone!</div>',
replace: true
}
});


效果



这是一个最简单的directive指令,其中有三个配置项:restrict,template,replace

这里使用了四种匹配的方式来实现hello这个指令,分别是AEMC,然后使用template中的语句,来replace掉了hello指令的部分。

template:'<div>Hi everyone!</div>'


1.解析最简单的指令hello:匹配模式restrict

一共有四种匹配的模式ACME



推荐使用元素和属性的方式,也就是EA的方式来进行匹配。

M(注释模式)下注意前后要有一个空格,不然无法正确匹配

当需要创建带有自己的模板的指令时,使用元素名称的方式创建

当需要为已有的HTML标签增加功能时,使用属性的方式创建

2.解析最简单的指令hello:template、templateUrl、$templateCache

在上述的例子中,我们使用了template,当中是html的字符串,但是这样不太好,如果内容很多,字符串就会过长,而且可能在js中要涉及大量的拼接,效率也不高。

template:'<div>Hi everyone!</div>'


所以我们引入templateUrl来引入一个独立的html文件作为模板,这样更方便编写

templateUrl:'hello.html'


另外还有一个$templateCache

var myModule = angular.module("MyModule", []);

//注射器加载完所有模块时,此方法执行一次
myModule.run(function($templateCache){
$templateCache.put("hello.html","<div>Hello everyone!!!!!!</div>");
});

myModule.directive("hello", function($templateCache) {
return {
restrict: 'AECM',
template: $templateCache.get("hello.html"),
replace: true
}
});


从cache字面意思上可以看出是要缓存,那么我们使用run这个方法,在加载完模块以后,先使用 $templateCache.put的方法将一段html的代码缓存到cache中。

当需要写template的时候,再使用 $templateCache.get的方法从换从中取出需要的代码就可以了。

3.解析最简单的指令hello:replace与transclude

replace设置为true,那么template中的html代码,会代替hello标签出现在html中,如果设置为false那么就不会代替hello标签,html中还是一个hello的标签存在

transclude是一个可以实现指令嵌套的选项。我们可以在hello标签中嵌套一个标签,下面来看一个小例子:

html

<!doctype html>
<html ng-app="MyModule">
<head>
<meta charset="utf-8">
</head>
<body>
<hello>
<div>这里是指令内部的内容。</div>
</hello>
</body>
<script src="framework/angular-1.3.0.14/angular.js"></script>
<script src="transclude.js"></script>
</html>


js

var myModule = angular.module("MyModule", []);
myModule.directive("hello", function() {
return {
restrict:"AE",
transclude:true,
template:"<div>Hello everyone!<div ng-transclude></div></div>"
}
});


我们将transclude设置为true,然后在template中有这么一句:

<div ng-transclude></div>


这个将会确定原来嵌套在hello标签中的内容显示的地方。

所以最后显示的效果是



指令执行的机制–compile与link

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  angularjs