【问题标题】:How to render innerHTML of tag as nested HTML如何将标签的innerHTML呈现为嵌套HTML
【发布时间】:2015-09-19 07:04:55
【问题描述】:

我正在使用 AngularJS 发出 GET 请求以接收 JSON 文档。从这个 JSON 文档中,经过一番遍历,我找到了一组额外的 JSON 文档。随着对该数组中每个对象的更多 JSON 遍历,生成的内部 JSON 文档是原始 HTML。

我试图在页面中显示这些原始 HTML 中的每一个,但是,我只能将它们作为原始文本等价物显示为纯文本,而不是实际呈现在 HTML 中。

在我的控制器中使用 $sce,我可以将数组的一个特定元素上的一个特定路径正确地渲染为 HTML,但不是全部。

这是我的代码:

//    controller:
$scope.latestEmails = function() {

$http.get('/emails/last/'+$scope.numberOfEmails).success(function(response) {
    $scope.insertHtmlHere = $sce.trustAsHtml(response.body[0].body[0].content);
        $scope.latestEmails = response.body;
    });

}

//    HTML
<div ng-bind-html="insertHtmlHere"></div> <!-- works for that one given element -->
        <ul>
            <li ng-repeat="email in latestEmails">{{email.body[0].content}} <!-- raw text displayed --></li>
        </ul>

ng-bind-html 正确替换了数组 HTML 中的第一个对象。 ng-repeat 部分只是将 HTML 文本块(未呈现为 HTML)放在列表​​中(屏幕截图:http://i.imgur.com/swmZ4Xe.png)。

有没有办法将我的 ng-repeat 中收到的 HTML 文本呈现为完整的 HTML?我可以使用不同的 AngularJS 方法来完成此任务吗?

任何帮助或建议将不胜感激!

【问题讨论】:

  • 当你这样做时会发生什么:

标签: javascript html json angularjs model-view-controller


【解决方案1】:

经过大量循环和连接技巧后,我找到了答案。基本上,我遍历 HTML 文档数组,将每个文档连接在一起并显示连接的 HTML。

这是我的解决方案代码:

// Controller:
    $http.get('/emails/last/'+$scope.numberOfEmails).success(function(response) {
    console.log('made a latestEmails get request');
    console.log(response);

    // get HTML of each email and concatenate together
    var concat;
    for(var i=0; i<response.body.length; i++) {
        var email = response.body[i].body[0].content;
        concat+=email;
    }
    // display the concatenated emails as pure HTML
    $scope.insertHtmlHere = $sce.trustAsHtml(concat);
});

// HTML
<div ng-bind-html="insertHtmlHere"></div>

希望对遇到此问题的其他人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多