2015-03-03 63 views
2

我不能得到$compileng-repeat手動工作。在這裏有一個類似的問題:ngRepeat in compiled by $compile does not work,但它不能解決問題,因爲我在範圍上手動調用$digest,但它仍然不起作用。

我所指的代碼是在這裏:

JS

angular.module('myApp', []); 

angular.module('myApp').directive('test', ['$compile', '$rootScope', '$timeout', 
    function ($compile, $rootScope, $timeout) { 
     var myScope = $rootScope.$new(); 
     myScope.numbers = [1, 2, 3]; 

     var html = '<div ng-repeat="number in numbers">{{ number }}</div>'; 
     var html2 = '<div>{{ numbers }}</div>'; 

     var returnObject = $compile(html)(myScope); 
     $timeout(function() { 
      myScope.$digest(); 
      console.log(returnObject); 
     }); 

     return {}; 
    } 
]); 

HTML

<html ng-app="myApp"> 

    <head> 
    ... 
    </head> 

    <body> 
     <h1 test>Hello Plunker!</h1> 
    </body> 

</html> 

鏈接plunkerhttp://plnkr.co/edit/RC1EILu16GPr0MGmSpcb?p=preview

如果將html變量切換爲html2,它將按預期內插並返回對象。但在目前的狀態下,我希望得到一個具有1,2,3的DIV集合...

回答

7

在內部,ng-repeat通過將元素添加到指令ng-repeat的父元素中起作用。你編譯的ng-repeat沒有父節點來添加它的元素,所以它不能工作。

添加父DIV(Plunk

var html = '<div><div ng-repeat="number in numbers">{{ number }}</div></div>'; 
var html2 = '<div>{{ numbers }}</div>'; 
var returnObject = $compile(html)(myScope); 
    $timeout(function() { 
     myScope.$digest(); 
     console.log(returnObject.children());