angularjs 从$http GET获取的HTML数据在Angular.js中无法正确显示

pdtvr36n  于 5个月前  发布在  Angular
关注(0)|答案(2)|浏览(45)

我定义了一个这样的控制器:

app.controller("home", function ($scope, $http, $common) {
    $http({
        method: "GET",
        url: '/posts/loadData'
    }).then(function (response) {
        //console.clear()
        if (typeof response.data.posts != 'undefined') {
            console.log(response.data.posts);
            $scope.posts = $common.arrangePosts(response.data.posts);
        }
    });
})

字符串
以及一种用于排列数据的服务:

app.service('$common', function ($timeout, $sce, $httpParamSerializerJQLike) {
    var that = this;
    this.arrangePosts = function (rawPosts) {
        var posts = [];
        
        $.each(rawPosts, function (key, value) {
            posts.push({
                          postId: value.postId, 
                          postLink: '/post/' + that.cleanString(value.title) + '/' + value.postId, 
                          title: value.title, 
                          summary: $sce.trustAsHtml(value.summary)
                       });
        });

        return posts;
    }
});


在HTML中使用值,如下所示:

<div class="widget fullwidth post-single">
        <h4 class="widget-title">Latest</h4>
        <div class="widget-content">
            <ul>
                <li ng-repeat="post in posts">
                    <h4 class="list-title"><a href="{{post.postLink}}">{{post.title}}</a></h4>
                    {{post.summary}}
                </li>
            </ul>
        </div>
    </div>


来自服务器的JSON格式的数据:

Object { postId="4",  title="asdf",  summary="<p>asdf</p>"}


但所有的HTML标签都打印在我的页面上,因为它是(像一个文本)的摘要。
在许多SO帖子中,人们建议使用$sce.trustAsHtml,但它对我不起作用。我下一步可以尝试什么?

b09cbbtk

b09cbbtk1#

您试过这个吗?

<div ng-bind-html='post.summary'></div>

字符串

g6baxovj

g6baxovj2#

你可以通过一个指令来解决这个问题。你知道吗,你可以在AngularJS中使用JQuery Lite来操作DOM?
这里有一个简单的例子:

angular.module("PostsDirective",[])
.directive("posts", function($sce){
return {
    link: function($scope, $element, $attrs){
        //the HTML you want to show 
        var post = "<div>hello world</div>";

        var posts = [post,post,post,post];

        //iterating through the list (_.each is a function from underscore.js)
        _.each(posts, function(element){
            //if you want to save the trusted html string in a var you can do this with getTrustedHtml
            //see the docs
            var safeHtml =  $sce.getTrustedHtml($sce.trustAsHtml(element));

            //and here you can use JQuery Lite. It appends the html string to the DOM
            //$element refers to the directive element in the DOM
            $element.append(safeHtml);
        });
    }
};
});

字符串
和html

<posts></posts>


这对你的HTML代码的可读性也很好。你可以在你的页面上的任何地方使用它。
顺便说一句:正如我所看到的,你直接从REST服务中获取HTML元素。为什么不直接获取数据并将其插入ng-repeat中呢?如果你传输所有的HTML,如果你有大量的数据,你会得到相当高的开销。

相关问题