Angular JS 中 指令详解

Angular JS的强大功能就在于其可以自定义很多指令,现在就指令做一下详细的剖析。

一个Angular js 指令(directive)需要指定一个唯一的名字(myDirective)和一个函数,其中返回一个对象,该对象包含该指令应有的一些行为,具体参见如下所有的属性。

angular.module('myApp', [])
.directive('myDirective', function() {
  return {
    restrict: String,
    priority: Number,
    terminal: Boolean,
    template: String or Template Function:
      function(tElement, tAttrs) (...},
    templateUrl: String,
    replace: Boolean or String,
    scope: Boolean or Object,
    transclude: Boolean,
    controller: String or
      function(scope, element, attrs, transclude, otherInjectables) { ... },
    controllerAs: String,
    require: String,
    link: function(scope, iElement, iAttrs) { ... },
    compile: // 返回一个对象或连接函数,如下所示:
      function(tElement, tAttrs, transclude) {
        return {
          pre: function(scope, iElement, iAttrs, controller) { ... },
          post: function(scope, iElement, iAttrs, controller) { ... }
        }
        // 或者
        return function postLink(...) { ... }

      }
   };
});

 

 

.directive('myDirective', function() {
  return {
    
    restrict: String,
    //可选属性,表明该指令可以以什么形式被声明,默认值为A,即属性。可以独立使用,也可以混合使用。
    E (Element 元素) <my-directive></my-directive>
    A (Attribute 属性) <div my-directive="expression"></div>
    C (Class 样式类) <div class="my-directive"></div>
    M (comment 注释) <!--directive:my-directive-->
    priority: Number,  
    
    //优先级属性,默认是0,ng-repeat的优先级是1000,这样做是为了保证他总是优于其他的指令运行
    相同优先级的指令,先声明的先运行。否则优先级高的先运行。    

  terminal: Boolean,  
  
    //是否停止运行比当前指令优先级低的指令,同优先级的指令依旧会被调用

  template: String or Template Function:       function(tElement, tAttrs) (...},
 
    //一段html代码或者是一个可以返回html片段的函数,注意
    templateUrl: String,
    //可以是外部HTML文件的路径,也能是一个返回外部HTML文件路径的函数,模板html的加载是异步的
    需要花费时间来编译和链接,所以使用环境是一个好的选择。

    replace: Boolean or String,    
    //默认值为false ,表明引用该指令的dom元素是否会被模板替换还是在内部嵌套,  
    scope: Boolean or Object,  

    //默认值是false,可以是true,也可以是一个对象。
    为true的时候,为此指令创建一个新的作用域,并且该作用域继承父级作用域
   
transclude: Boolean,  

    //默认false,可以将当前dom中的html内容嵌入到指令中使用ng-transclude的位置。

   controller: String or       function(scope, element, attrs, transclude, otherInjectables) { ... },     controllerAs: String,     require: String,     link: function(scope, iElement, iAttrs) { ... },     compile: // 返回一个对象或连接函数,如下所示:       function(tElement, tAttrs, transclude) {         return {           pre: function(scope, iElement, iAttrs, controller) { ... },           post: function(scope, iElement, iAttrs, controller) { ... }         }         // 或者         return function postLink(...) { ... }       }    }; });
posted @ 2018-03-04 23:51  pikzas  阅读(149)  评论(0编辑  收藏  举报