【问题标题】:ng-repeat not loading data after html has been compiledng-repeat 在 html 编译后不加载数据
【发布时间】:2013-11-05 05:53:26
【问题描述】:

我有一个指令,它复制了一些 html,其中包括一个控制器和一个 ng-repeat。我编译 html 并将其粘贴到 dom 中。我可以看到新的 html 正在获取新编译的控制器的范围,但是如果数据是异步加载的,那么 ng-repeat 将不起作用。

我创建了一个 plunker http://plnkr.co/edit/jCjW26PCwlmKVTohja0s?p=preview,它显示了我遇到的问题。

index.html

<div class="parent-div">
    <div class="put-compiled-data-in-here" compile-html>
        <!-- copied html goes in here -->
    </div>
    <div ng-controller="CopiedController" class="copy blue">
        <h1>{{name}}</h1>
        <div ng-repeat="p in projects">
            <h1>{{p.name}}</h1>
        </div>
    </div>
</div>

控制器

app.controller('CopiedController', function($scope, slowService){
   $scope.projects = slowService.loadSlowData();
   $scope.name = "Inside Copied Controller";
 }); 

复制和编译html的指令

app.directive('compileHtml', function ($compile, $rootScope, $parse) {
    return {
        restrict: 'A',
        link: function (scope, ele, attrs) {
            var html = jQuery('.copy').clone().removeClass('.blue').addClass('.pink');
            var el = angular.element(html);
            ele.append(el);
            $compile(ele.contents())(scope);
        }
     };
});

慢速服务(又名 ajax):

app.service('slowService', function($timeout) {
    this.loadSlowData = function() {
        return $timeout(function() {
          return [{name:"Part 2a"},
                 {name:"Part 2b" } ]
          }, 300);
     };    
});

任何帮助将不胜感激。

【问题讨论】:

  • 您是否真的希望复制的部分再次加载数据,这就像您正在尝试做的那样?还是只想在页面的两个不同位置显示相同的数据?如果是后者,那么您应该将数据放在范围内,以便双方都能看到它。也许使用共享服务。
  • 在克隆上操作类有什么意义......然后只使用它的内部html?使用ng-class

标签: angularjs angularjs-directive angularjs-ng-repeat


【解决方案1】:

检查

    http://plnkr.co/edit/l7o5EFC3863ZI4cxvuos?p=preview

更改以下内容

    <div ng-controller="CopiedController" class="put-compiled-data-in-here" compile-html>




    app.directive('compileHtml', function($compile, $rootScope, $parse) {
        return {
            template: $('.copy').html(),
            restrict: 'A',
            link: function(scope, ele, attrs) {
                // var html = jQuery('.copy').clone().removeClass('.blue').addClass('.pink');
                // var el = angular.element(html);
                // ele.append(el);
                // $compile(ele.contents())(scope);
                ele.removeClass('blue').addClass('pink');
            }
        };
    });

【讨论】:

  • 这很有效,谢谢。你能解释一下为什么这行得通,而我的尝试没有奏效,因为我认为在链接阶段编译会做同样的事情。
  • 不是链接阶段的编译不起作用。只是当你得到$('.copy')时,你得到的jQuery对象并不是渲染出来的。
【解决方案2】:

您可能应该删除“。”来自 removeClass 和 addClass 运算符

var html = jQuery('.copy').clone().removeClass('blue').addClass('pink');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 2017-01-13
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多