Angular 自定义指令详解

1.命名:

     可以使用普通字符串,也可以使用驼峰法来命名一个指令,例如 firstDirective, 但在使用它时需要以 - 分割: first-directive。

2.创建方式:

    Angularjs的指令创建有四种形式,比如创建的指令hello:

(1)元素名(E):

<hello></hello>

(2)标签属性(默认)(A):

<div hello></div>

(3)标签样式类的形式(C):

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

(4)注释(M)(注释号注意有个空格): 

<!-- directive: hello -->
3.指令的创建JS代码:

myApp.directive('hello',function(){  
    return {  
        restrict:'AE',  
        template:'<div>hello everyone!</div>',  
        //transclude:false  
        replace:false  
    }  
}); 

a.restrict 值可以是以下几种:

  • E 作为元素名使用,A 作为属性使用,C 作为类名使用,M 作为注释使用

         restrict 默认值为 EA, 即可以通过元素名和属性名来调用指令。

b.replace 解析

初始 html:

  E: <hello><div>angular指令学习</div></hello>   

    如果replace设置为false,最终页面展现的html结果如下:

  E: <hello><div>hello everyone!</div></hello>    
   如果replace设置为true,原有 dom 节点被覆盖,最终页面展现的html结果如下:
  E:<div>hello everyone!</div>     


c.如果想把html 里原有的DOM 结构保留,要设置transclude的值,并利用 ng-transclude 保存原有 html:

myApp.directive('hello',function(){  
    return {  
        restrict:'ACEM',  
        template:'<div>hello everyone!<div ng-transclude></div></div>', //通过ng-transclude,将默认的 HTML 保存在div标签里
        transclude:true  
    }  
}); 


HTML 如下显示:(原有的 html 得以保留)

  E:<hello><div>hello everyone!<div ng-transclude><div class="ng-scope">angular 指令学习</div></div></hello>   

transclude这个配置很重要,可以实现指令的互相嵌套。

 参考:
 ①:http://stackoverflow.com/questions/15285635/how-to-use-replace-of-directive-definition
 ②: http://www.runoob.com/angularjs/angularjs-directives.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章