我试图通过使用ng-bind-html和filter来显示我在div.testData中收到的html内容。我已经在我的应用中加入了'ngSanitize'。但不知何故,它只是部分起作用。好像,过滤器没有得到应用。当我创建本地文件并检查时,它工作正常,但是当我在项目环境中使用相同的代码时,它不起作用。
样本数据:
$scope.userProfile.Information = '<p>Hello, this is sample data to test html.</p>';
显示的输出是:
'<p>Hello, this is sample data to test html.</p>'
期望的输出是:
'Hello, this is sample data to test html.'
请帮我解决这个问题。
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<div class="testData" ng-bind-html= "userProfile.Information | to_trusted"></div>
过滤:
app.filter('to_trusted', ['$sce', function($sce){
return function(text) {
var doc = new DOMParser().parseFromString(text, "text/html");
var rval= doc.documentElement.textContent;
//console.log(rval);
return $sce.trustAsHtml(rval);
};
}]);
你可以尝试使用下面的代码,因为你有这个plunker的给定工作示例。请检查一下..
控制器:
app.filter('to_trusted', ['$sce', function($sce){
return function(text) {
var txt = document.createElement("textarea");
txt.innerHTML = text;
return $sce.trustAsHtml(txt.value);
};
}]);
答案是here已经。
app.filter('to_trusted', ['$sce', function($sce){
return $sce.trustAsHtml;
}]);
var app = angular.module("Profile",[])
app.directive('toTrusted',function(){
return function(scope,element,attr){
var result = attr.data
var input_val = result.replace(/</g, "<").replace(/>/g, ">").replace(/ /g, "\n");
element[0].innerHTML = input_val;
scope.use_recusrive(element[0].firstElementChild,element[0])
}
})
app.controller("ProfileCtrl", function($scope, $rootScope,$sce){
$scope.valid_input = '<div> div 1 sample <p> div1 indide p tag .</p></div><p> p tag 2.</p> <div>DIV 2 Sample </div>';
$scope.use_recusrive = function(dom,p_node){
if(!dom)
return;
var s_dom = dom.firstElementChild
if(!s_dom){
var text_content = dom.textContent||'';
var tag_name = dom.tagName
var new_text_content = text_content+' to be renedered as '+"'"+tag_name+"'"+' tag.';
dom.textContent = new_text_content;
/*if(s_dom.nextElementSibling)
$scope.use_recusrive(s_dom.nextElementSibling,dom)*/
}else{
$scope.use_recusrive(dom.firstElementChild,dom)
}
var nex_sibling = dom.nextElementSibling
if(nex_sibling){
$scope.use_recusrive(nex_sibling,dom)
}
}
})
div{
color:black;
font-weight:700;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="Profile" ng-controller="ProfileCtrl">
<div to-trusted data={{valid_input}} ></div>
</body>