首頁  >  文章  >  web前端  >  AngularJS中取消對HTML片段轉義的方法範例_AngularJS

AngularJS中取消對HTML片段轉義的方法範例_AngularJS

WBOY
WBOY原創
2016-05-16 16:22:221092瀏覽

今天嘗試用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 部分
複製程式碼 程式碼如下:


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn