今天尝试用 rails 做后端提供 json 格式的数据, angularjs 做前端处理 json 数据,其中碰到 angularjs 获取的是一段 html 文本,如果直接使用 data-ng-bind 的话是被转义过的,使用 data-ng-bind-html 则可以取消转义。
但是直接使用 data-ng-bind-html 的话会提示错误
在我这里 Angular 通过 API 或取的所有文章中,每篇文章有个 html_body 属性是经过 Markdown 或者 Org 渲染过的 HTML 片段。
在通过 API 获取 JSON 数据后,使用 AngularJS 提供的 angular.forEach 方法对每个 post 的 html_body 进行标记,并将结果保存为 trustedBody, 然后在 HTML 中使用 data-ng-bind-html="post.trustedBody" 即可以取消转义。
AngularJS 部分
$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怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号