2016-07-30 34 views
1

爲了創建自定義組件系統,我在搞AngularJS。我已經提出了一個關於我的組件系統here的問題,所以你可以檢查一下,以便理解我的系統應該如何工作(也許它已經改變了一些,但基本的想法保持不變)。AngularJS - 爲什麼我不能訪問鏈接函數中的子元素?

我試圖通過組件指令和ng-include-屬性元素尋找一個子元素,但不知何故事情並不正確。

指令

我的指令如下:

.directive("raqComponent", ["ComponentsStyles", 
function(componentsStyles){ 
    return { 
     restrict: "E", 
     scope: { 
      name: "@" 
     }, 
     template: "<div ng-include=\"'/Components/' + name + '.htm'\"></div>", 
     controller: function($scope, $timeout){ 
      componentsStyles.stylesheets.push($scope.name); 

      if(components[$scope.name] !== undefined){ 
       if(components[$scope.name].getData !== undefined){ 
        components[$scope.name].getData($scope); 
       } 
      } 
     }, 
     link: function(scope, elem, attrs){ 
      if(components[scope.name] !== undefined){ 
       if(components[scope.name].link !== undefined){ 
        console.log("Children:", elem.children()); 
        var elemTarget = elem; 
        components[scope.name].link(elemTarget); 
       } 
      } 
     } 
    }; 
}]) 

在這個指令,用於爲每個組件,我用NG-include指令,包括我心愛的部件標記。組件在單獨的文件中實現以增加模塊性。

一旦頁面使用的分量,DOM看起來像這樣的實際網頁上顯示:

enter image description here

現在,元素raq-component與屬性ng-include一個子元素。此元素具有一個子元素,它是特定組件的自定義標記的根元素。像這樣:

<div class="navbar"> 
    <div class="container"> 
     <div class="row"> 
      <div class="col-md-12"> 
       <div class="navbar-items-container"> 
        <div class="navbar-items"> 
         <div ng-repeat="item in items" class="navbar-item"> 
          <p>{{item.name}}</p> 
         </div> 
        </div> 
       </div> 
      </div> 
     </div> 
    </div> 
</div> 

但是,當我嘗試訪問子元素時,我無法做到這一點。我在打印指令子元素是這樣的:

if(components[scope.name].link !== undefined){ 
    console.log("Children:", elem.children()); 
    var elemTarget = elem; 
    components[scope.name].link(elemTarget); 
} 

和孩子是這樣的:

enter image description here

除了沒有,由於某種原因!但爲什麼呢?我已經使用了像第一(),最後()和eq(0)等功能的JQuery,但他們沒有做任何事情。有什麼奇怪的是,我可以看到,雖然使用Javascript孩子不JQuery的:

enter image description here

那麼爲什麼我不能訪問鏈接功能的子元素?

回答

2

鏈接函數實際上是一個後鏈接函數,將在子元素被編譯和鏈接時執行。

然而,從角的正式文件:

注意,包含templateUrl指令子元素不會 已編譯和鏈接,因爲它們正在等待他們的 模板異步加載和自己的編譯和鏈接 已被暫停,直到發生這種情況。

雖然它沒有告訴,該指令ngInclude就像設置templateUrl,其模板請求是異步的。

這意味着調用鏈接函數時,ngInclude尚未準備好DOM操作。而你無法得到這些孩子的元素。

快速解決方案:

將代碼放在$scope.evalAsync,它將指令的DOM操縱後執行。

相關問題