AnngularJS---自訂指令

來源:互聯網
上載者:User

標籤:

AngularJS提供了一系列的內建指令,如ng開頭的指令,同時AngularJS也允許使用者自訂指令。

目錄:

  1.自訂指令

  2.使用自訂指令

  3.自訂指令的內嵌使用

自訂指令

 

AngularJS中使用directive()方法來自訂指令,directive() 方法可以接受兩個參數:

  name(字元):指令的名字,用來在視圖中引用特定的指令

  factory_function(函數):這個函數返回一個對象,其中定義了指令的全部行為

例如:建立一個test指令:

var app = angular.module(‘myApp‘,[]);    app.directive(‘hello‘,function(){        return {            restrict:‘AECM‘,            template:‘<div>hello world</div>‘,            replace:true        };    });

 

說明:

在directive方法的第二個函數參數中,返回了一個對象,欄位的意義如下:

restrice:定義了標籤的使用方法,一共四種,分別是AECM

template:定義標籤的模板。裡面是用於替換自訂標籤的字串

repalce:是否替換

另外還有transclude:標識是否嵌套

使用自訂指令

指令在html中的使用有4中方法,分別對應restrice的標籤的4個使用方法AECM

A:屬性

<div hello></div>--------><div>hello world</div>

E:元素

<hello></hello>--------><div hello="">hello world</div>

C:樣式(class的值)

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

M:注釋

<!-- directive:hello ----------->各個版本不一樣
自訂指令的內嵌使用
app.directive(‘test‘,function(){    return {        restrict:‘AECM‘,        template:‘<div>hello <div ng-transclude></div> world</div>‘,        transclude:true    };});

說明:自訂指令的內嵌使用需要將transclude欄位賦值為true,template中使用ng-transclude來確定內嵌的位置。

執行個體代碼如下:

<!DOCTYPE><html ng-app="myApp"><head>     <meta charset="utf-8" />     <script src="https://code.angularjs.org/1.3.1/angular.min.js"> </script></head><body>    <div>0</div>    <hello></hello>    <div>1</div>    <div hello></div>    <div>2</div>    <div class="hello"></div>    <div>3</div>    <!-- directive:hello -->    <div>4</div>    <hello>3333</hello>    <div>5</div>    <test>4444</test>    <script type="text/javascript">        var app = angular.module(‘myApp‘,[]);        app.directive(‘hello‘,function(){            return {                restrict:‘AECM‘,                template:‘<div>hello world</div>‘,                replace:true            };        });                app.directive(‘test‘,function(){            return {                restrict:‘AECM‘,                template:‘<div>hello <div ng-transclude></div> world</div>‘,                transclude:true            };        });    </script></body></html>

 

 

AnngularJS---自訂指令

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.