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

pdtvr36n  于 2024-01-05  发布在  Angular
关注(0)|答案(2)|浏览(209)

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

  1. app.controller("home", function ($scope, $http, $common) {
  2. $http({
  3. method: "GET",
  4. url: '/posts/loadData'
  5. }).then(function (response) {
  6. //console.clear()
  7. if (typeof response.data.posts != 'undefined') {
  8. console.log(response.data.posts);
  9. $scope.posts = $common.arrangePosts(response.data.posts);
  10. }
  11. });
  12. })

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

  1. app.service('$common', function ($timeout, $sce, $httpParamSerializerJQLike) {
  2. var that = this;
  3. this.arrangePosts = function (rawPosts) {
  4. var posts = [];
  5. $.each(rawPosts, function (key, value) {
  6. posts.push({
  7. postId: value.postId,
  8. postLink: '/post/' + that.cleanString(value.title) + '/' + value.postId,
  9. title: value.title,
  10. summary: $sce.trustAsHtml(value.summary)
  11. });
  12. });
  13. return posts;
  14. }
  15. });


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

  1. <div class="widget fullwidth post-single">
  2. <h4 class="widget-title">Latest</h4>
  3. <div class="widget-content">
  4. <ul>
  5. <li ng-repeat="post in posts">
  6. <h4 class="list-title"><a href="{{post.postLink}}">{{post.title}}</a></h4>
  7. {{post.summary}}
  8. </li>
  9. </ul>
  10. </div>
  11. </div>


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

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


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

b09cbbtk

b09cbbtk1#

您试过这个吗?

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

字符串

g6baxovj

g6baxovj2#

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

  1. angular.module("PostsDirective",[])
  2. .directive("posts", function($sce){
  3. return {
  4. link: function($scope, $element, $attrs){
  5. //the HTML you want to show
  6. var post = "<div>hello world</div>";
  7. var posts = [post,post,post,post];
  8. //iterating through the list (_.each is a function from underscore.js)
  9. _.each(posts, function(element){
  10. //if you want to save the trusted html string in a var you can do this with getTrustedHtml
  11. //see the docs
  12. var safeHtml = $sce.getTrustedHtml($sce.trustAsHtml(element));
  13. //and here you can use JQuery Lite. It appends the html string to the DOM
  14. //$element refers to the directive element in the DOM
  15. $element.append(safeHtml);
  16. });
  17. }
  18. };
  19. });

字符串
和html

  1. <posts></posts>


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

展开查看全部

相关问题