I'm trying to display the html content which I receive in my div.testData by using ng-bind-html together with filter. I've already included 'ngSanitize' in my app. But somehow, it works only partially. Seem like, filter is not getting applied. It works fine when I create a local file and check, but doesn't work when I use the same code in my project environment.
Sample data:
$scope.userProfile.Information = '<p>Hello, this is sample data to test html.</p>';
The output displayed is:
'<p>Hello, this is sample data to test html.</p>'
Desired output is :
'Hello, this is sample data to test html.'
Please help me fix this.
HTML:
<div ng-app="myApp" ng-controller="myCtrl">
<div class="testData" ng-bind-html= "userProfile.Information | to_trusted"></div>
Filter:
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);
};
}]);
答案 0 :(得分:1)
You can try like the below code as you have your given working example with this plunker. Please check that too..
Controller:
app.filter('to_trusted', ['$sce', function($sce){
return function(text) {
var txt = document.createElement("textarea");
txt.innerHTML = text;
return $sce.trustAsHtml(txt.value);
};
}]);
答案 1 :(得分:0)
Answer is here already.
app.filter('to_trusted', ['$sce', function($sce){
return $sce.trustAsHtml;
}]);
答案 2 :(得分:0)
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)
}
}
})
&#13;
div{
color:black;
font-weight:700;
}
&#13;
<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>
&#13;