2013-11-28 57 views
3

我有以下幾點:伍重複優先

app.directive("myDirective", function($compile) { 
    return { 
     replace: true, 
     scope: {}, 
     template: "<div></div>", 
     link: function(scope, elem) { 

      scope.list = [1, 2, 3, 4, 5]; 
      $compile("<div my-list></div>")(scope, function(clone) { 
       // Why the ng-repeat isn't compiled yet? 
       alert(clone[0].outerHTML); 
       elem.html(clone); 
      }); 
     } 
    }; 
}); 

app.directive("myList", function() { 
    return { 
     replace: true, 
     template: "<ul><li ng-repeat=\"item in list\">{{item}}</li></ul>" 
    }; 
}); 

<div my-directive></div>

誰能告訴我爲什麼我的<li>'s是不是在我的alert

http://jsfiddle.net/AlexFigueiredoo/jNceZ/

回答

4

好了,所以我要補充一點,以@ dawuut的答案。

使用'0'冷卻將alert包裹在$timeout中將起作用,因爲直到角度$digest週期結束時纔會觸發超時。

因此,當您首次在父指令中調用alert時,子代尚未編譯(它們都有自己的作用域)。

+0

非常感謝! :) – meriadec

4

Here is your updated Fiddle

它的工作使用$超時指令(http://docs.angularjs.org/api/ng.$timeout)以 '0' 的冷卻時間。聽起來有點棘手,但...

所以,注入$在你的控制器超時,然後在回調:

$timeout(function() { 
    alert(clone[0].outerHTML); 
}, 0); 
+2

我認爲OP對「爲什麼」這個行爲感興趣。那麼,爲什麼添加'$ timeout'會有所作爲。 –

2

我猜你的編譯<div my-list></div>的任務與的產生simultanously計算li s在子目錄中。

這可以解釋爲什麼您的alert發生在ling-repeater的完整生成之前。

因此,$timeout對於線性化兩個任務很有用。

的原因是這裏的解釋:Why timeout(0) is sometimes necessary?