欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

AngularJS中取消對HTML片段轉(zhuǎn)義的方法例子

 更新時(shí)間:2015年01月04日 11:58:57   投稿:junjie  
這篇文章主要介紹了AngularJS中取消對HTML片段轉(zhuǎn)義的方法例子,在一些需要顯示HTML的地方,就要取消AngularJS的轉(zhuǎn)義,本文就介紹了這種方法,需要的朋友可以參考下

今天嘗試用 Rails 做后端提供 JSON 格式的數(shù)據(jù), AngularJS 做前端處理 JSON 數(shù)據(jù),其中碰到 AngularJS 獲取的是一段 HTML 文本,如果直接使用 data-ng-bind 的話是被轉(zhuǎn)義過的,使用 data-ng-bind-html 則可以取消轉(zhuǎn)義。

但是直接使用 data-ng-bind-html 的話會(huì)提示錯(cuò)誤

復(fù)制代碼 代碼如下:

Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context.

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

在我這里 Angular 通過 API 或取的所有文章中,每篇文章有個(gè) html_body 屬性是經(jīng)過 Markdown 或者 Org 渲染過的 HTML 片段。

在通過 API 獲取 JSON 數(shù)據(jù)后,使用 AngularJS 提供的 angular.forEach 方法對每個(gè) post 的 html_body 進(jìn)行標(biāo)記,并將結(jié)果保存為 trustedBody, 然后在 HTML 中使用 data-ng-bind-html="post.trustedBody" 即可以取消轉(zhuǎn)義。

AngularJS 部分

復(fù)制代碼 代碼如下:

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 部分
復(fù)制代碼 代碼如下:

<div class="post-body markup-body" data-ng-bind-html="post.trustedBody"></div>

相關(guān)文章

最新評論