AngularJS提供了一系列的内置指令,如ng开头的指令,同时AngularJS也允许用户自定义指令。

目录:

  1.自定义指令

  2.使用自定义指令

  3.自定义指令的内嵌使用

自定义指令

AngularJS中使用directive()方法来自定义指令,directive() 方法可以接受两个参数:

  name(字符):指令的名字,用来在视图中引用特定的指令

  factory_function(函数):这个函数返回一个对象,其中定义了指令的全部行为

例如:创建一个test指令:

var app = angular.module('myApp',[]);
app.directive('hello',function(){
return {
restrict:'AECM',
template:'<div>hello world</div>',
replace:true
};
});

说明:

在directive方法的第二个函数参数中,返回了一个对象,字段的意义如下:

restrice:定义了标签的使用方法,一共四种,分别是AECM

template:定义标签的模板。里面是用于替换自定义标签的字符串

repalce:是否替换

另外还有transclude:标识是否嵌套

使用自定义指令

指令在html中的使用有4中方法,分别对应restrice的标签的4个使用方法AECM

A:属性

<div hello></div>--------><div>hello world</div>

E:元素

<hello></hello>--------><div hello="">hello world</div>

C:样式(class的值)

<div class="hello"></div>------><div class="hello">hello world</div>

M:注释

<!-- directive:hello ----------->各个版本不一样

自定义指令的内嵌使用

app.directive('test',function(){
return {
restrict:'AECM',
template:'<div>hello <div ng-transclude></div> world</div>',
transclude:true
};
});

说明:自定义指令的内嵌使用需要将transclude字段赋值为true,template中使用ng-transclude来确定内嵌的位置。

实例代码如下:

<!DOCTYPE>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<script src="https://code.angularjs.org/1.3.1/angular.min.js"> </script>
</head>
<body>
<div></div>
<hello></hello>
<div></div>
<div hello></div>
<div></div>
<div class="hello"></div>
<div></div>
<!-- directive:hello -->
<div></div>
<hello></hello>
<div></div>
<test></test>
<script type="text/javascript">
var app = angular.module('myApp',[]);
app.directive('hello',function(){
return {
restrict:'AECM',
template:'<div>hello world</div>',
replace:true
};
}); app.directive('test',function(){
return {
restrict:'AECM',
template:'<div>hello <div ng-transclude></div> world</div>',
transclude:true
};
});
</script>
</body>
</html>

最新文章

  1. 从2-3-4树到红黑树(下) Java与C的实现
  2. SQL各种语句、函数
  3. java执行顺序
  4. document对象(二)
  5. div模拟textarea
  6. Android ImageView显示本地图片
  7. C# 程序性能提升篇-1、装箱和拆箱,枚举的ToString浅析
  8. 【原创分享】python获取乌云最新提交的漏洞,邮件发送
  9. C语言位运算符:与、或、异或、取反,左移和右移
  10. Non-negative Partial Sums(单调队列)
  11. HTTP协议及HTTP包
  12. String 类的实现(1)浅拷贝存在的问题
  13. struts2使用模型传值
  14. CentOS7下 Java、Tomcat、MySQL、Maven热部署
  15. Problem : 1022 ( Train Problem I )
  16. 20165220 Java第三周学习总结
  17. 十七、springcloud(三)服务的注册与调用
  18. 第三次Sprint-最后冲刺
  19. [HTML] 动态修改input placeholder的颜色
  20. [清华集训2015 Day1]主旋律-[状压dp+容斥]

热门文章

  1. 如何在Form++开源组态平台添加硬件采集接口
  2. 2016-08-05(1) ng-options的用法详解
  3. PHP时区配置
  4. OD20
  5. 百川sdk----自己的WebViewClient不被执行
  6. WIN32服务程序(一):创建服务
  7. python sproto支持64位有符号整数
  8. Largest Rectangle in Histogram
  9. kafka性能基准测试
  10. javscript创建Emitter