【问题标题】:How to $compile html template and append to DOM with AJAX return JSON array (List widget add items)如何使用 AJAX 返回 JSON 数组 $compile html 模板并附加到 DOM(列表小部件添加项目)
【发布时间】:2015-10-24 15:31:20
【问题描述】:

遇到这个非常令人困惑的问题。我想要做的就像下面的代码:

$scope.addArtis = function(list) {
    list.forEach(function(article){
        $scope.article = article;
        var html = $compile($templateCache.get('template/articlelist/articleitem.html'))($scope);
            $element.append(html);
        });
    };
};

虽然模板是存储在缓存中的 string-html-template。

[list]是ajax请求返回的数据,会是一个json数组。现在对每个数组对象,编译不同的模板并将其附加到 DOM。

但现在代码结果是我得到了 [list.length] 相同的数据(JSON 数组中的最后一个对象)编译的 HTML 附加到 DOM。我在想也许 $scope.article 已更改为最后一个 JSON 数组对象,但我不知道如何处理?

我发现如果在 HTML 模板中使用 ng-repeat 可以解决一些问题。但是如果我只想编译单个并在 for 循环中附加到 DOM 怎么办?

【问题讨论】:

  • 尝试使用 $rootScope.new() 在循环中创建一个新范围
  • @samschonstal 你能给我一些代码示例吗?

标签: javascript angularjs compilation


【解决方案1】:

可能是这样的:

.controller('myController', function($rootScope)  {   

$scope.addArtis = function(list) {
    list.forEach(function(article){
        var scope = $rootScope.new();
        scope.article = article;
        var html = $compile($templateCache.get('template/articlelist/articleitem.html'))(scope);
            $element.append(html);
        });
    };
};
});

【讨论】:

  • 谢谢山姆。这样我的页面就可以正常工作了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-27
  • 1970-01-01
  • 2021-06-01
  • 1970-01-01
  • 2016-01-10
  • 2013-03-11
  • 2021-09-06
相关资源
最近更新 更多