关于angular 自定义directive

关于angular 自定义directive的小结

首先我们创建一个名为"expander"的自定义directive指令:

angular.module("myApp",[]).directive("expander",function(){
    return{
    //directive的一些属性(键值对形式)如下:
    /*
    restrict:'EA',
    replace:true,
    transclude:true,
    scope:{...},
    template:....,
    templateURL:....,
    link:function(scope,element,attrs){
      
    }
    */
  }
});

主要有如下几个属性:

  1. restrict
    E: 表示该directive仅能以element方式使用,即:<my-dialog></my-dialog>
    A: 表示该directive仅能以attribute方式使用,即:<div my-dialog></div>
    EA: 表示该directive既能以element方式使用,也能以attribute方式使用

  2. transclude
    是否嵌入,true/false。

  3. scope
    当你写上该属性时,就表示这个directive不会从它的controller里继承$scope对象,而是会重新创建一个。
  4. tempalte 
    替换自定义directive的真实HTML代码
  5. templateUrl
    替换自定义directive的模板路径
  6. link
    可以简单理解为,当directive被angular 编译后,执行该方法

link中的第一个参数scope基本上就是你说的上面写的那个scope

element简单说就是$('expander')

attrs是个map,内容是你这个directive上的所有属性,例如:你在页面上如果这样写了directive:

<expander type="modal" animation="fade"></expander>

attrs就是:
{
type: 'modal',
animation: 'fade'
}

posted @ 2016-01-11 16:33  郭靖丶  阅读(134)  评论(0编辑  收藏  举报