一,angularjs編譯的三個階段
1.將html轉換為DOM;
2.搜索匹配的directive,按照priority排序(默認優先級是0,ng-repeat為1000),並執行directive上的complie方法;
3.執行directive上的link方法,該方法主要進行scope綁定及事件綁定。
二.complie屬性是一個function,, 在其中可以更改dom元素,或者進行dom元素的事件綁定等
complie:function(tElement,tAttrs,transclude){
return ...
}可以返回一個對象或函數,直接返回一個函數的話就是postLink函數,這個函數其實就是單獨的link函數,也可以返回一個對象,包含prelink和postlink,如果compile函數定義了參數后,將無視link函數,因為complie里面返回的就是需要執行的link函數。
參數解釋:
tElement 正在執行該指令的當前dom元素的jquery對象;
tAttrs 正在執行該指令的當前dom元素的屬性;
transclude 模版替換之前的內容
三. link(scope,iElement,iAttrs,controller)
1.link函數代表的是complie返回的postLink函數;
2.preLink表示在編譯階段之后,在子元素被鏈接之前執行;
3.postLink會在所有子元素被鏈接之后執行;
- var i=0;
- angular.module('myApp',[])
- //定義第一個指令:customTags
- .directive('customTags',function(){
- return {
- restrict:'ECAM',
- template:'<div>{{ user.name }}</div>',
- replace:true,
- //定義了compile就不需定義link,當compile返回一個方法這個方法就是link
- //tElement 正在執行該指令的當前dom元素的jquery對象
- //tAttrs 正在執行該指令的當前dom元素的屬性
- compile:function(tElement,tAttrs,transclude){
- //第一個指令的編譯階段...
- console.log('customTags compile 編譯階段...');
- //若要改變dom元素,應在compile中做,此處在當前dom元素中添加一個<span>
- tElement.append(angular.element('<span> {{user.count}}</span>'));
- return {
- //pre:編譯階段之后執行
- pre:function preLink(scope,iElement,iAttrs,controller){
- console.log('customTags preLink..');
- },
- //post:所有子元素指令的post都執行后執行,此處設置了dom元素的點擊事件
- post:function postLink(scope,iElement,iAttrs,controller){
- iElement.on('click',function(){
- scope.$apply(function(){
- scope.user.name=' click after';
- scope.user.count= ++i;
- });
- });
- console.log('customTags post end.');
- console.log('');
- }
- };
- //compile也可直接返回一個方法,這就是 postLink,也就是上面的post
- /*return function (){
- console.log('compile return this function')
- }*/
- },
- //進行scope綁定及事件綁定
- link:function(scope,iElement,iAttrs,bookListController){
- //link不會再執行了,因為這里定義的就是postLink
- }
- }
- })
- //定義第二個指令:customTags2
- .directive('customTags2',function(){
- return {
- restrict:'ECAM',
- replace:true,
- compile:function(tElement,tAttrs,transclude){
- console.log('customTags2 compile 編譯階段...');
- return {
- pre:function preLink(){
- console.log('customTags2 preLink..');
- },
- post:function postLink(){
- console.log('customTags2 post end.');
- }
- };
- }
- }
- })
- .controller('firstController',['$scope',function($scope){
- $scope.users=[
- {id:10,name:'張三',count:0}
- ]
- }]);
4.執行順序:先編譯,在執行preLink,最后postLink在倒着執行,即compile與pre-link的執行順序是依次執行,但是post-link正好相反.;
5.參數解釋:
scope
指令用來在其內部注冊監聽器的作用域。
iElement
iElement參數代表實例元素,指使用此指令的元素。在postLink函數中我們應該只操作此元素的子元素,因為子元素已經被鏈接過了。
iAttrs
iAttrs參數代表實例屬性,是一個由定義在元素上的屬性組成的標准化列表,可以在所有指令的鏈接函數間共享。會以JavaScript對象的形式進行傳遞。
controller
controller 參 數 指 向 require 選 項 定 義 的 控 制 器 。 如 果 沒 有 設 置 require 選 項 , 那 么controller參數的值為undefined。
控制器在所有的指令間共享,因此指令可以將控制器當作通信通道(公共API)。如果設置了多個require,那么這個參數會是一個由控制器實例組成的數組,而不只是一個單獨的控制器。