標籤:
前言:
前面寫的有些亂,並且有些羅嗦,以後會注意的。希望我寫的文章能協助大家。
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