我正在使用AngularJS 1.5.8。
我试图在视图中绑定{{card.reading}}
,但数据呈现为文本
HTML
<div ng-app="myApplication" ng-controller="postController as tarot">
<ul>
<li class="card" ng-repeat="card in tarot">
<img class="card" src="app/images/cards/{{card.value}}.png" alt="card.name">
<article>{{card.reading | unsafe}}</article>
</li>
</ul>
</div>`
的JavaScript
var app = angular.module('myApplication', []);
app.controller('postController', function($scope, $http, $filter, $sce) {
$scope.$sce = $sce;
var url = './api.php/tarot';
$http.get(url).success(function(response) {
$scope.tarot = php_crud_api_transform(response).tarot;
});
});
app.filter('unsafe', function($sce){
return $sce.parseAsHtml;
});
JSON的例子
{
"id":1,
"name": "Test",
"value": "1",
"reading": "<h2>Lorem Ipsum</h2><p>Lorem ipsum</p>"
}
答案 0 :(得分:0)
如此更新HTML应该可以解决问题..
<div ng-app="myApplication" ng-controller="postController as tarot">
<ul>
<li class="card" ng-repeat="card in tarot">
<img class="card" src="app/images/cards/{{card.value}}.png" alt="card.name">
<article ng-bind-html="card.reading"></article>
</li>
</ul>
</div>`
答案 1 :(得分:0)
谢谢,它现在已经解决了。
<强>的JavaScript 强>
var app = angular.module('myApplication', ['ngSanitize'])
.controller('postController', ['$scope', '$http', '$sce',
function postController($scope, $http, $sce) {
var url = './api.php/tarot';
$http.get(url).success(function(response) {
$scope.tarot = php_crud_api_transform(response).tarot
});
$scope.explicitlyTrustedHtml = $sce.trustAsHtml();
}
]);
和你建议的HTML。 :)
答案 2 :(得分:0)
还有另一种解决方案。你可以稍微修改你的代码,它会起作用。
<div ng-app="myApplication" ng-controller="postController as tarot">
<ul>
<li class="card" ng-repeat="card in tarot">
<img class="card" src="app/images/cards/{{card.value}}.png" alt="card.name">
<article ng-bind-html="card.reading | unsafe"></article>
</li>
</ul>
</div>`
将过滤器更改为,
app.filter('unsafe', function($sce) {
return function(text) {
return $sce.trustAsHtml(text);
}
});
这样可行。