我面临的问题是我从服务器获取一些代表 html 的字符串 我需要解析某些节点的样式属性,然后使用 Angular 在 View 中显示此 html。
所以我看到这个答案 https://stackoverflow.com/a/494348/1022726这有助于我创造 一个来自字符串的 html 节点,然后我检查每个项目并更改样式。 最后我用innerHTML的值做$sce.trustAsHtml。
我有这个代码http://plnkr.co/edit/HUfAGR2uNMwb48rqXbkk?p=preview
<div ng-bind-html="trustedHtml"></div>
function($scope, $sce) {
var s = '<h1 style="color: red; font-size: 16px;">Subheader</h1><p style="font-size: 12px;">text</p>';
var div = document.createElement('div');
div.innerHTML = s;
$(div).find("*").each(function () {
$(this).height('100px');
});
$scope.trustedHtml = $sce.trustAsHtml(div.innerHTML);
}]);
我想知道是否有更好的方法来解析表示 html 的字符串,然后在 View 中显示该 html。 如有任何帮助,我们将不胜感激。
最佳答案
你可以把它做成一个过滤器,比如
app.filter('trusted', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
});
然后在你的html中你可以有
<div ng-bind-html="text | trusted"></div>
关于javascript - 如何将 $sce.trustAsHtml 与某些 HTML 节点一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31193195/