我正在努力从JSON字符串中显示HTML代码。您可以在地址中看到HTML标记。有什么方法可以正确显示它吗?
我的模板是:
<div ng-app ng-controller="jsonp_example">
<ul ng-repeat="item in data">
<li>{{item.ID}}</li>
<li>{{item.post_title}}</li>
<li ng-bind-html-unsafe="getContent(obj)">{{item.custom_fields.sponsor_address}}</li>
<li>
<img src="{{item.custom_fields.sponsor_logo}}" width="100">
<ul>
<li>
<hr>
</li>
</ul>
</li>
</ul>
</div>
脚本:
function jsonp_example($scope, $http) {
$scope.getContent = function (obj) {
return obj.custom_fields.sponsor_address
};
var url = "https://eventident.com/api/getposts/?auth_key=s2mEus39R296M5F6n343A3dh9c62f7cm&custom_post=sponsors&callback=JSON_CALLBACK";
$http.jsonp(url).success(function (data) {
$scope.data = data.result;
});
}
请随时修改我的jsfiddle:http://jsfiddle.net/1295z4bc/
答案 0 :(得分:3)
Did you include angular-sanitize.js as a dependency ? (as a script and as angular module dependency)
Also, you don't need to {{}}
with ng-bind-html, just
<li ng-bind-html="item.custom_fields.sponsor_address"></li>
will do.
答案 1 :(得分:2)
You need to include the ngSanitize service and directly use ng-bind-html
.
Here is an updated jsfiddle from yours: http://jsfiddle.net/e01xj547/9/
答案 2 :(得分:1)
You might need to explicitly trust the html string by using the $sce
service. E.g var trustedHtml=$sce.trustAsHtml('<em>My html string</em>');
In your case to following usage would be appropirate:
function jsonp_example($scope, $http, $sce) {
$scope.getContent = function (obj) {
return $sce.trustAsHtml(obj.custom_fields.sponsor_address);
};
var url = "https://eventident.com/api/getposts/?auth_key=s2mEus39R296M5F6n343A3dh9c62f7cm&custom_post=sponsors&callback=JSON_CALLBACK";
$http.jsonp(url).success(function (data) {
$scope.data = data.result;
});
}
Example usage: http://jsbin.com/zopenoqipi/2/edit?html,js,output