Я определил контроллер следующим образом:
app.controller("home", function ($scope, $http, $common) {
$http({
method: "GET",
url: '/posts/loadData'
}).then(function (response) {
//console.clear()
if (typeof response.data.posts != 'undefined') {
console.log(response.data.posts);
$scope.posts = $common.arrangePosts(response.data.posts);
}
});
})
и услугу по организации данных:
app.service('$common', function ($timeout, $sce, $httpParamSerializerJQLike) {
var that = this;
this.arrangePosts = function (rawPosts) {
var posts = [];
$.each(rawPosts, function (key, value) {
posts.push({
postId: value.postId,
postLink: '/post/' + that.cleanString(value.title) + '/' + value.postId,
title: value.title,
summary: $sce.trustAsHtml(value.summary)
});
});
return posts;
}
});
используя значения в html следующим образом:
<div class="widget fullwidth post-single">
<h4 class="widget-title">Latest</h4>
<div class="widget-content">
<ul>
<li ng-repeat="post in posts">
<h4 class="list-title"><a href="{{post.postLink}}">{{post.title}}</a></h4>
{{post.summary}}
</li>
</ul>
</div>
</div>
Данные, поступающие с сервера в форме JSON:
Object { postId="4", title="asdf", summary="<p>asdf</p>"}
но все теги html печатаются на моей странице, как есть (например, текст).
Во многих сообщениях SO люди предлагали использовать $sce.trustAsHtml
но не работали для меня. Пожалуйста, предложите в любом случае решить мою проблему.
Любая помощь будет оценена. !!
вы пробовали это?
<div ng-bind-html='post.summary'></div>
Вы можете решить это по директиве. Знаете ли вы, что вы можете использовать JQuery Lite внутри AngularJS для управления DOM?
Вот краткий пример:
angular.module("PostsDirective",[])
.directive("posts", function($sce){
return {
link: function($scope, $element, $attrs){
//the HTML you want to show
var post = "<div>hello world</div>";
var posts = [post,post,post,post];
//iterating through the list (_.each is a function from underscore.js)
_.each(posts, function(element){
//if you want to save the trusted html string in a var you can do this with getTrustedHtml
//see the docs
var safeHtml = $sce.getTrustedHtml($sce.trustAsHtml(element));
//and here you can use JQuery Lite. It appends the html string to the DOM
//$element refers to the directive element in the DOM
$element.append(safeHtml);
});
}
};
});
И html
<posts></posts>
Это также очень приятно для читаемости вашего HTML-кода. И вы можете использовать его повсюду на своей странице.
BTW: Как я вижу, вы получаете элементы HTML непосредственно из REST-Service. Почему бы вам не получить только данные и вставить их в ng-repeat? Если вы переносите весь HTML-код, вы получаете довольно высокие накладные расходы, если у вас есть множество данных.