这篇文章主要为大家纤细介绍了 AngularJS directive 返回对象属性的相关内容,感兴趣的小伙伴们可以参考一下
AngularJS 诞生于 Google 是一款优秀的前端 JS 框架,已经被用于 Google 的多款产品当中。AngularJS 有着诸多特性,最为核心的是:MVC、模块化、自动化双向数据绑定、语义化标签、依赖注入,等等。
写在前面:由于 directive 部分是 angularjs 中的重中之重,所以会分多篇章进行讲解。本章主要讲解 directive 返回对象中比较简单的属性
angularjs 中使用. directive() 来定义指令,该方法接收两个参数:name(指令的名字)、factory_function(该函数定义指令的全部行为,返回一个对象)
栗子:
- //index.js
- angular.module('myApp', []);
- myApp.directive('myDirective',
- function() {
- return {};
- });
返回对象中包含以下属性及方法:
1:restrict:String
该属性用来说明 myDirective 指令在 DOM 中是以何种形式被声明的(即在 html 中该把它用在什么地方)
该属性可选值有:E(元素)、A(属性,默认值)、C(类名)、M(注释),可单独使用,也可组合使用
看到过一种说法:如果是想要自定义一个独立的指令功能,即该指令独立完成一系列操作,不用依附其他元素、属性等,就将该指令定义为元素;如果想要用该指令来扩展某已存在指令的功能,便将其定义为属性。不知道这么理解是否合理,但确实也是一个很好的可以借鉴的选择方法标准
2:priority:Number
该属性用来定义指令的优先级(默认为 0,ngRepeat 是所有内置指令中优先级最高的,为 1000),优先级高的先执行。
3:terminal:Boolean
该属性与 priority 属性有一定联系,它用来判断是否停止运行当前元素上比本指令优先级低的指令,但相同优先级的依旧会执行
栗子:
- //index.js
- angular.module('myApp',[])
- .directive('myDirective',function() {
- return {
- restrict: 'AE',
- priority: 1,
- template: '<div>hello world</div>'
- };
- })
- .directive('myDirective1',function() {
- return {
- restrict: 'AE',
- priority: 3,
- terminal: true
- };
- })
- <!-- index.html -->
- <div my-directive my-directive1></div>
如果没有定义 myDirective1 指令,结果浏览器会显示 hello world,但添加了 myDirective1 指令之后,并将其优先级 priority 设置比 myDirective 大,且在 myDirective1 上设置属性 terminal 属性为 true 之后,便会停止 myDirective 指令的执行。
4:template:String/Function
该属性定义一个模板(即在 html 文件中使用到该指令的部分会替换该模板内容,所以该模板主要是 html 格式)
属性有两种形式:一段 html 文本、一个返回模板字符串的函数,并且该函数接收两个参数:tElement,tAttrs
5:templateUrl:String/Function
当模板内容比较多时,直接嵌套在 template 中会显得冗余,可以采取将模板代码单独存放在一个文件中,这时就会需要引入文件,templateUrl 便可以做到
属性也有两种形式:一个代表外部 html 文件路径的字符串、一个返回外部 html 文件路径字符串的函数,该函数接收两个参数:tElement,tAttrs
6:replace:Boolean
该属性默认值为 false,指明模板是会被当做子元素插入到调用该指令的元素内部,还是覆盖取代调用该指令的元素。
栗子:
- //index.js
- angular.module('myApp',[])
- .directive('myDirective',function() {
- return {
- restrict: 'A',
- template: '<div>hello world</div>',
- replace: true/false
- };
- })
- <!-- index.html -->
- <my-directive>
- </my-directive>
当 repalce 取 false 时,浏览器端源码呈现为
7:transclude:Boolean
栗子:
- <!-- index.html -->
- <div my-directive>
- world
- </div>
像这个例子中,如果指令内部有内容,一般情况下 template 模板会直接覆盖替换掉该内容,但现在我想把它保留下来,这时 transclude 就派上用途了
- //index.js
- angular.module('myApp',[])
- .dirctive('myDirective',function() {
- return {
- restrict: 'EA',
- transclude: true,
- template: '<div>hello <span ng-transclude></span></div>'
- };
- })
来源: http://www.phperz.com/article/17/0221/266530.html