$ compile和ng-repeat没有返回正确的元素

sah*_*wah 2 javascript compilation angularjs ng-repeat

我不能$compile手动上班ng-repeat.这里有一个类似的问题:由$ compile编译的ngRepeat不起作用,但它没有解决这里的问题,因为我手动调用$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 {};
    }
]);
Run Code Online (Sandbox Code Playgroud)

HTML:

<html ng-app="myApp">

    <head>
    ...
    </head>

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

</html>
Run Code Online (Sandbox Code Playgroud)

链接到plunker:http://plnkr.co/edit/RC1EILu16GPr0MGmSpcb?p = preview

如果将html变量切换为html2它将插入并按预期返回对象.但是在目前的状态下,我希望得到1,2,3的DIV集合......

Joe*_*ger 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());
Run Code Online (Sandbox Code Playgroud)