AngularJS中取消對HTML片段轉義的方法例子,

來源:互聯網
上載者:User

AngularJS中取消對HTML片段轉義的方法例子,

今天嘗試用 Rails 做後端提供 JSON 格式的資料, AngularJS 做前端處理 JSON 資料,其中碰到 AngularJS 擷取的是一段 HTML 文本,如果直接使用 data-ng-bind 的話是被轉義過的,使用 data-ng-bind-html 則可以取消轉義。

但是直接使用 data-ng-bind-html 的話會提示錯誤
複製代碼 代碼如下:
Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.

HTML 片段需要先使用 $sce.trustAsHtml(html_in_string) 將標記為信任,然後才可以使用 data-ng-bind-html="html_in_string" 取消轉義。

在我這裡 Angular 通過 API 或取的所有文章中,每篇文章有個 html_body 屬性是經過 Markdown 或者 Org 渲染過的 HTML 片段。

在通過 API 擷取 JSON 資料後,使用 AngularJS 提供的 angular.forEach 方法對每個 post 的 html_body 進行標記,並將結果儲存為 trustedBody, 然後在 HTML 中使用 data-ng-bind-html="post.trustedBody" 即可以取消轉義。

AngularJS 部分
複製代碼 代碼如下:
Blog.controller('PostsController', function ($scope, $http, $sce) {
  $scope.posts = [];

  $scope.syncPosts = function () {
    var request = $http.get('http:/localhost:3000/posts.json');
    request.success(function (response) {
      $scope.posts = angular.forEach(angular.fromJson(response), function (post) {
        post.trustedBody = $sce.trustAsHtml(post.html_body);
      });
    });
  };

  $scope.syncPosts();
});

HTML 部分
複製代碼 代碼如下:
<div class="post-body markup-body" data-ng-bind-html="post.trustedBody"></div>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.