【问题标题】:$compile and ng-repeat not returning correct element$compile 和 ng-repeat 没有返回正确的元素
【发布时间】:2015-03-03 04:26:56
【问题描述】:

我无法让 $compile 手动使用 ng-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 ...

【问题讨论】:

    标签: javascript angularjs compilation ng-repeat


    【解决方案1】:

    在内部,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());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-03
      • 2012-10-03
      • 1970-01-01
      • 2016-07-21
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多