DIV CSS 佈局教程網

AngularJS 中取消 HTML 片段轉義的方法與示例
編輯:關於JavaScript     

最近嘗試用 Rails 作為後端提供 JSON 數據,由 AngularJS 在前端進行處理。過程中遇到一個情況: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.

要解決這個問題,需要先用 $sce.trustAsHtml(html_in_string) 把 HTML 片段標記為「可信」,然後才能用 data-ng-bind-html="html_in_string" 取消轉義。

在我的場景裡,Angular 通過 API 拉取的所有文章都有一個 html_body 屬性,它是經過 Markdown 或 Org 渲染後的 HTML 片段。因此在拿到 JSON 數據後,我使用 AngularJS 提供的 angular.forEach 遍歷每一篇文章,把它的 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('https://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>

通過 $sce.trustAsHtml 標記可信內容,再配合 data-ng-bind-html 綁定,就能安全地把後端返回的 HTML 片段渲染到頁面上。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved