天天看點

【AngularJS】—— 8 自定義指令

AngularJS支援使用者自定義标簽屬性,在不需要使用DOM節點操作的情況下,添加自定義的内容。

前面提到AngularJS的四大特性:

  1 MVC

  2 子產品化

  3 指令

  4 雙向資料綁定

下面将會介紹如下的内容:

  1 如何自定義指令

  2 自定義指令的使用

  3 自定義指令的内嵌使用

  如何自定義指令:

  Angular是基于子產品的架構,是以上來肯定要建立一個自己的子產品:

var myAppModule = angular.module("myApp",[]);      

  然後在此子產品基礎上建立指令directive

myAppModule.directive("xingoo",function(){
                return{
                    restrict:'AECM',
                    template:'<div>hello my directive</div>',
                    replace:true
                }
            });      

  其中,xingoo是我們自定義标簽的名字,後面跟着它的方法函數。

  函數return了一個鍵值對組合,其中定義了标簽的使用方法、屬性等等内容。

  那麼看看它都定義了哪些内容吧:

  1 restrict:定義了标簽的使用方法,一共四種,分别是AECM

  2 template:定義标簽的模闆。裡面是用于替換自定義标簽的字元串

  3 replace:是否支援替換

  4 transclude:是否支援内嵌

  如何使用指令:

  上面提到了标簽的四種使用方法,即AECM。

  A attribute屬性:當做屬性來使用

<div xingoo></div>      

  E element元素:當做标簽元素來使用

<xingoo></xingoo>      

  C class類:當做CSS樣式來使用

<div class="xingoo"></div>      

  M comments注釋:當做注釋使用(這種方式在1.2版本下親測不可用!)

<!-- directive:xingoo -->
<div></div>      

  一般來說推薦,當做屬性和元素來使用。

  當想要在現有的html标簽上擴充屬性時,采用屬性的方式。

  當想要自定義标簽時,采用标簽的形式。

  想要使用那種方式,必須要在定義directive中的restrict裡面聲明對應的字母。

  指令的内嵌使用:

  因為标簽内部可以嵌套其他的标簽,是以想要在自定義标簽中嵌套其他的元素标簽,則需要:

  1 使用transclude屬性,設定為true。

  2 并使用ng-transclude屬性,定義内部嵌套的位置。

  代碼如下:

myAppModule.directive("test",function(){
                return{
                    restrict:'AECM',
                    transclude:true,
                    template:"<div>haha! <div ng-transclude></div> wuwu!</div>"
                }
            });      

  全部代碼

<!doctype html>
<html ng-app="myApp">
    <head>
         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
         <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
    </head>
    <body>

        <xingoo></xingoo>
        <div xingoo></div>
        <div class="xingoo"></div>
        <!-- directive:xingoo -->
        <div></div>
        <hr>
        <xingoo>3333</xingoo>
        <hr>
        <test>4444</test>


        <script type="text/javascript">
            var myAppModule = angular.module("myApp",[]);

            myAppModule.directive("xingoo",function(){
                return{
                    restrict:'AECM',
                    template:'<div>hello my directive</div>',
                    replace:true
                }
            });

            myAppModule.directive("test",function(){
                return{
                    restrict:'AECM',
                    transclude:true,
                    template:"<div>haha! <div ng-transclude></div> wuwu!</div>"
                }
            });
        </script>
    </body>
</html>      

  運作結果

【AngularJS】—— 8 自定義指令