AngularJs-指令1

來源:互聯網
上載者:User

標籤:

前言:

  前面寫的有些亂,並且有些羅嗦,以後會注意的。希望我寫的文章能協助大家。

1,什麼是指令

  簡單的說,指令是angularjs在html頁面中建立一套自己能識別的標籤元素、屬性、類和注釋,用來達到功能複用的目的。

2,建立指令
<!DOCTYPE html><html ng-app="MyModule"><head>    <meta charset="utf-8">    <title></title></head><body>    <!-- 指令的第一種模式 E -->    <hello></hello>        <!-- 指令的第二種模式 A -->    <div hello></div>        <!-- 指令的第三種模式 C -->    <div class="hello"></div>        <!-- 指令的第四種模式 M-->    <!-- directive:hello -->    <div></div>    <script src="js/angular-1.3.0.js"></script>    <script src="js/hello.js"></script></body></html>

 從上面的代碼可以看出,指令有四種建立方式,上面的四種模式對應下面js代碼中 restrict屬性AEMC。

var myModule = angular.module("MyModule",[]);
//建立指令myModule.directive(‘hello‘,function(){ return{ restrict:‘AEMC‘, // 匹配模式 A:屬性 E:元素 M:注釋 C:Class template:‘<div>hello world</div>‘, replace:true }})

可以自己動手建立。

3,指令--restrict

 restrict意思是約束,限定的意思,在此就是限定這個指令可用的四種匹配模式。

 這麼多模式,我們該在什麼情境下用呢?

  •    A:屬性指令,如果想在已有的標籤再添加指令,推薦使用這個方式。
  •    E:元素指令,官方推薦屬性,可以自訂標籤顯示。
  •    M:注釋指令,一般不使用,容易刪除。別人不好理解。
  •    C:樣式類指令,一般不使用,容易誤解。

4,指令--template

  模板(程式碼片段)的使用我們有4中方式。

  •   template:‘<div>hello world</div>‘,把程式碼片段直接複製給模板屬性
  •       templateUrl:‘tmpl/hello.html‘,引用外部檔案,當你的模板有很多代碼的時候使用。
  •       template:$templateCache.get(‘hello.html‘),使用模板緩衝,這個方法解決一個模板複用的情況,hello.html是一個虛擬檔案,可不建立
  •       模板可以為空白,直接在 html檔案裡面寫 <hello>hello</hello>

 

// 注射器載入所有模組時,此方法執行一次,緩衝模板myModule.run(function($templateCache){    // console.log("323"); html檔案是虛擬,可以任意起名字    $templateCache.put(‘hellos.html‘,"<div>hello everyone..</div>")})myModule.directive(‘hello‘,function($templateCache){    return{        restrict:‘AECM‘,        template:$templateCache.get(‘hellos.html‘),        replace:true    }})

 

5,指令--replace

  replace意思替換,代替的意思。如果進行指令嵌套的時候,需要改變下。

html:

    <hello>        <div>nihao</div>    </hello>

js:

myModule.directive(‘hello‘,function(){    return{        restrict:‘AE‘,        transclude:true,        template:‘<div>hello everyone <div ng-transclude></div></div>‘,    }})

在這裡使用了 ng-transclude 方法,這個方法的作用是讓angularjs把指令嵌套的內容放到 帶有ng-transclude屬性的標籤中去。

6,指令--compile(編譯階段)

angularjs預設的函數,我們可以自訂該函數,當指令dome變化完畢就會執行。

7,指令--link(連結階段)

在link函數裡面可以給元素繫結事件。

8,總結

  關於指令的其他屬性和方法,需要大家到官網去找自己看。我這邊也會把這節代碼上傳到我的github(https://github.com/NIKing/angularJs.git)上。

 

  

AngularJs-指令1

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.