angularjs 學習 指令學習一

指令(directive)

指令是AngularJs自定義的HTML元素或屬性;

一個簡單的指令定義方法如下:
angular.module('app').directive('directiveName',function(){
    return {
        restrict:'E',
        template:string,
    };
})

該方法定義了一個名爲directiveName的指令,該指令作爲html中元素方式存在, 以<directive></directive>調用指令
當然,上述方法只是一個簡單的指令定義方法,複雜的指令需要指令中其它屬性的配合;

完整的創建指令的僞代碼爲
    angular.module('app').directive('directiveName',function(){
    return {
        restrict:'E',
        priority:number,
        template:string,
        templateUrl:string,
        replace:bool,
        transclude:bool,
        scope:bool or object,
        controller:function($scope,$element,$attr,$transclude)
        require:string,
        link:function postLink(scope,iElement,iAttrs){...},
        compile:function compile(tElement,tAttrs,transclude){
            return {
                pre:function preLink(scope,iElement,iAttrs,controller){...},
                post:function postLink(scope,iElement,iAttrs,controller){...}
            }
        }
    };
})
詳細解釋
  1. restrict:描述了指令作爲元素名稱、元素屬性或樣式存在,可選值爲
    E 元素 <directive></directive>
    A 屬性 <div directive=""></div>
    C 樣式類 <directive class=directive></directive>
    三者可以組合

  2. priority:描述了指令的優先級,大的優先級會先運行,優先級相同的指令,按照其定義的順序執行

  3. terminal: 停止運行比該優先級還低的指令,但相同優先級的指令仍會運行
.directive('helloWorld',function(){
         return {
                 restrict:'EA',
                 template:'<div>hello world</div>',
                 priority:100,
                 terminal:true
     }
 })
     .directive('helloTwo',function(){
         return {
             restrict:'EA',
             template:'<div>JunJunDaXia</div>',
             priority:120,
             terminal:true
         }
     })
 ```
 helloTwo 指令會覆蓋 helloWorld指令

4. template: 模板會替代指令包裹的內容
5. templateUrl:加載服務器上的模板
6. replace: 默認爲false,模板會幫當做子元素插入到此指令的元素內部;如果爲true,則模板替換指令所在位置

```javascript
    angular.module('app').directive('helloWorld',function(){
        return {
            restrict:'E',
            template:<div>hello world</div>,
            replace:true
        };
    })




<div class="se-preview-section-delimiter"></div>

替換後的Html爲
<div>hello world</div>
如果 repalce爲false,則替換後的HTML爲
<hello-world><div>hello world</div></hello-world>

  1. transclude: 此屬性爲ture時,指令會刪除原來的內容,如果模板中使用了ng-transclude指令,則刪除的內容會被重新插入
 <div hello-world>123</div>
.directive('helloWorld',function(){
        return {
                restrict:'EA',
                template:'<div>hello world <span ng-transclude></span> </div>',
                transclude:true,
    }
})




<div class="se-preview-section-delimiter"></div>

解析後的html爲:

<div hello-world=""><div>hello world <span ng-transclude=""><span class="ng-scope">123</span></span> </div></div>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章