Decode HTML entity in Angular JS - javascript

How do i decode HTML entity in text using angular JS.
I have the string
""12.10 On-Going Submission of ""Made Up"" Samples.""
I need a way to decode this using Angular JS. I found a way to do that using javascript here but I am sure thats wont work for Angular. Need to get back the original string on the UI which would look like
""12.10 On-Going Submission of ""Made Up"" Samples.""

You can use the ng-bind-html directive to display it as an html content with all the html entities decoded. Just make sure to include the ngSanitize dependency in your application.
DEMO
JAVASCRIPT
angular.module('app', ['ngSanitize'])
.controller('Ctrl', function($scope) {
$scope.html = '"12.10 On-Going Submission of ""Made Up"" Samples."';
});
HTML
<body ng-controller="Ctrl">
<div ng-bind-html="html"></div>
</body>

If you don't want to use ngSanitize, you can do it this way:
in your controller:
$scope.html = '"12.10 On-Going Submission of ""Made Up"" Samples."'
$scope.renderHTML = function(html_code)
{
var decoded = angular.element('<textarea />').html(html_code).text();
return $sce.trustAsHtml(decoded);
};
And in the template:
<div ng-bind-html="renderHTML(html)"></div>
Just make sure you inject $sce in your controller

I have similar issue, but don't need to use result value on UI. This issue was resolved by code from angular ngSanitize module:
var hiddenPre=document.createElement("pre");
/**
* decodes all entities into regular string
* #param value
* #returns {string} A string with decoded entities.
*/
function decodeEntities(value) {
if (!value) { return ''; }
hiddenPre.innerHTML = value.replace(/</g,"<");
// innerText depends on styling as it doesn't display hidden elements.
// Therefore, it's better to use textContent not to cause unnecessary reflows.
return hiddenPre.textContent;
}
var encoded = '<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>';
var decoded = decodeEntities(encoded);
document.getElementById("encoded").innerText=encoded;
document.getElementById("decoded").innerText=decoded;
#encoded {
color: green;
}
#decoded {
color: red;
}
Encoded: <br/>
<div id="encoded">
</div>
<br/>
<br/>
Decoded: <br/>
<div id="decoded">
</div>

Related

HTML document preserve the new lines and spaces when using innerText

I am new to webdevelopment. So, Here, I have textAngular. In this I a, showing html document. Now, I want to show the text of the document only but that should be with the formatting as it is in the .html file. So,Right now my code is like -
here data is the html file content, you can say it's a string which has the html file content.Now,
$scope.htmlOriginalDoc = parser.parseFromString(data, 'text/html');
$rootScope.data.htmlDocument = $scope.htmlOriginalDoc.body.innerText;
So, Here when I get this that time I am getting all the data of that file, but when I see it it is like just a text document it is not having any new lines,I mean its not preserving the new line or spaces .So, How can I achieve this ?
Basically you need to compile it from string, then bind it with ngSanitize. To preserve the white space wrap with <pre> tags.
var app = angular.module('myApp', ['ngSanitize']);
app.controller('myCtrl', function($scope, $sce) {
$scope.html = "<div style=\"color:red;font-size:24px;\"> T e s t </div>"; // string
$scope.html = $sce.trustAsHtml($scope.html);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-sanitize.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div style="white-space: pre;"> <!-- instead of <pre> -->
<div ng-bind-html="html"></div>
</div>
</div>

AngularJS - Convert JSON string into HTML codes [duplicate]

Is it possible to create an HTML fragment in an AngularJS controller and have this HTML shown in the view?
This comes from a requirement to turn an inconsistent JSON blob into a nested list of id: value pairs. Therefore the HTML is created in the controller and I am now looking to display it.
I have created a model property, but cannot render this in the view without it just printing the HTML.
Update
It appears that the problem arises from angular rendering the created HTML as a string within quotes. Will attempt to find a way around this.
Example controller :
var SomeController = function () {
this.customHtml = '<ul><li>render me please</li></ul>';
}
Example view :
<div ng:bind="customHtml"></div>
Gives :
<div>
"<ul><li>render me please</li></ul>"
</div>
For Angular 1.x, use ng-bind-html in the HTML:
<div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>
At this point you would get a attempting to use an unsafe value in a safe context error so you need to either use ngSanitize or $sce to resolve that.
$sce
Use $sce.trustAsHtml() in the controller to convert the html string.
$scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml(someHtmlVar);
ngSanitize
There are 2 steps:
include the angular-sanitize.min.js resource, i.e.:
<script src="lib/angular/angular-sanitize.min.js"></script>
In a js file (controller or usually app.js), include ngSanitize, i.e.:
angular.module('myApp', ['myApp.filters', 'myApp.services',
'myApp.directives', 'ngSanitize'])
You can also create a filter like so:
var app = angular.module("demoApp", ['ngResource']);
app.filter("trust", ['$sce', function($sce) {
return function(htmlCode){
return $sce.trustAsHtml(htmlCode);
}
}]);
Then in the view
<div ng-bind-html="trusted_html_variable | trust"></div>
Note: This filter trusts any and all html passed to it, and could present an XSS vulnerability if variables with user input are passed to it.
Angular JS shows HTML within the tag
The solution provided in the above link worked for me, none of the options on this thread did. For anyone looking for the same thing with AngularJS version 1.2.9
Here's a copy:
Ok I found solution for this:
JS:
$scope.renderHtml = function(html_code)
{
return $sce.trustAsHtml(html_code);
};
HTML:
<p ng-bind-html="renderHtml(value.button)"></p>
EDIT:
Here's the set up:
JS file:
angular.module('MyModule').controller('MyController', ['$scope', '$http', '$sce',
function ($scope, $http, $sce) {
$scope.renderHtml = function (htmlCode) {
return $sce.trustAsHtml(htmlCode);
};
$scope.body = '<div style="width:200px; height:200px; border:1px solid blue;"></div>';
}]);
HTML file:
<div ng-controller="MyController">
<div ng-bind-html="renderHtml(body)"></div>
</div>
Fortunately, you don't need any fancy filters or unsafe methods to avoid that error message. This is the complete implementation to properly output HTML markup in a view in the intended and safe way.
The sanitize module must be included after Angular:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-sanitize.js"></script>
Then, the module must be loaded:
angular.module('app', [
'ngSanitize'
]);
This will allow you to include markup in a string from a controller, directive, etc:
scope.message = "<strong>42</strong> is the <em>answer</em>.";
Finally, in a template, it must be output like so:
<p ng-bind-html="message"></p>
Which will produce the expected output: 42 is the answer.
I have tried today, the only way I found was this
<div ng-bind-html-unsafe="expression"></div>
ng-bind-html-unsafe no longer works.
This is the shortest way:
Create a filter:
myApp.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
And in your view:
<div ng-bind-html="customHtml | unsafe"></div>
P.S. This method doesn't require you to include the ngSanitize module.
on html
<div ng-controller="myAppController as myCtrl">
<div ng-bind-html-unsafe="myCtrl.comment.msg"></div>
OR
<div ng-bind-html="myCtrl.comment.msg"></div
on controller
mySceApp.controller("myAppController", function myAppController( $sce) {
this.myCtrl.comment.msg = $sce.trustAsHtml(html);
works also with $scope.comment.msg = $sce.trustAsHtml(html);
I found that using ng-sanitize did not allow me to add ng-click in the html.
To solve this I added a directive. Like this:
app.directive('htmldiv', function($compile, $parse) {
return {
restrict: 'E',
link: function(scope, element, attr) {
scope.$watch(attr.content, function() {
element.html($parse(attr.content)(scope));
$compile(element.contents())(scope);
}, true);
}
}
});
And this is the HTML:
<htmldiv content="theContent"></htmldiv>
Good luck.
Just did this using ngBindHtml by following angular(v1.4) docs,
<div ng-bind-html="expression"></div>
and expression can be "<ul><li>render me please</li></ul>"
Make sure you include ngSanitize in the module's dependencies.
Then it should work fine.
Another solution, very similar to blrbr's except using a scoped attribute is:
angular.module('app')
.directive('renderHtml', ['$compile', function ($compile) {
return {
restrict: 'E',
scope: {
html: '='
},
link: function postLink(scope, element, attrs) {
function appendHtml() {
if(scope.html) {
var newElement = angular.element(scope.html);
$compile(newElement)(scope);
element.append(newElement);
}
}
scope.$watch(function() { return scope.html }, appendHtml);
}
};
}]);
And then
<render-html html="htmlAsString"></render-html>
Note you may replace element.append() with element.replaceWith()
there is one more solution for this problem using creating new attribute or directives in angular.
product-specs.html
<h4>Specs</h4>
<ul class="list-unstyled">
<li>
<strong>Shine</strong>
: {{product.shine}}</li>
<li>
<strong>Faces</strong>
: {{product.faces}}</li>
<li>
<strong>Rarity</strong>
: {{product.rarity}}</li>
<li>
<strong>Color</strong>
: {{product.color}}</li>
</ul>
app.js
(function() {
var app = angular.module('gemStore', []);
app.directive(" <div ng-show="tab.isSet(2)" product-specs>", function() {
return {
restrict: 'E',
templateUrl: "product-specs.html"
};
});
index.html
<div>
<product-specs> </product-specs>//it will load product-specs.html file here.
</div>
or
<div product-specs>//it will add product-specs.html file
or
<div ng-include="product-description.html"></div>
https://docs.angularjs.org/guide/directive
you can also use ng-include.
<div class="col-sm-9 TabContent_container" ng-include="template/custom.html">
</div>
you can use "ng-show" to show hide this template data.
here is the solution make a filter like this
.filter('trusted',
function($sce) {
return function(ss) {
return $sce.trustAsHtml(ss)
};
}
)
and apply this as a filter to the ng-bind-html like
<div ng-bind-html="code | trusted">
and thank to Ruben Decrop
Use
<div ng-bind-html="customHtml"></div>
and
angular.module('MyApp', ['ngSanitize']);
For that, you need to include angular-sanitize.js,
for example in your html-file with
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-sanitize.js"></script>
Here's a simple (and unsafe) bind-as-html directive, without the need for ngSanitize:
myModule.directive('bindAsHtml', function () {
return {
link: function (scope, element, attributes) {
element.html(scope.$eval(attributes.bindAsHtml));
}
};
});
Note that this will open up for security issues, if binding untrusted content.
Use like so:
<div bind-as-html="someHtmlInScope"></div>
Working example with pipe to display html in template with Angular 4.
1.Crated Pipe escape-html.pipe.ts
`
import { Pipe, PipeTransform } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
#Pipe({name : 'keepHtml', pure : false})
export class EscapeHtmlPipe implements PipeTransform{
constructor(private sanitizer : DomSanitizer){
}
transform(content){
return this.sanitizer.bypassSecurityTrustHtml(content);
}
}
`
2. Register pipe to app.module.ts
import {EscapeHtmlPipe} from './components/pipes/escape-html.pipe';
declarations: [...,EscapeHtmlPipe]
Use in your template
<div class="demoPipe" [innerHtml]="getDivHtml(obj.header) | keepHtml">
getDivHtml() { //can return html as per requirement}
Please add appropriate implementation for getDivHtml in associated component.ts file.
Just simple use [innerHTML], like below:
<div [innerHTML]="htmlString"></div>
Before you needed to use ng-bind-html...

$sce.trustAsHtml is not evaluating a javascript string (or trustAsJs For that matter);

My server has a json endpoint that returns a html/js string, looks similar to such:
"\r\n\r\n<div id=\'myEditor\" name=\"myEditor\">\r\n\r\n\t\t\r\n\t</div>\r\n\r\n\r\n\r\n\r\t<script type=\"text/javascript\" src=\"/MyEditor/WebResource.axd?...\:">\r\n\r\n\t<script>\r\n\t..."
I want to inject this with angular into a div, and have it execute the javascript as well.
First attempt:
function myCtrl ($sce) {
$http.get(endpoint).then(function (response) {
$scope.html = response.data;
$scope.editorHtml = $sce.trustAsHtml($scope.html); //also tried trustAsJs
}
}
html:
<div ng-bind-html="editorHtml"></div>
I noticed that if I return a pure html string those tags get rendered, however a pure javascript tags do NOT get evaluated. How do I get it to evaulate these tags? AngularJS version 1.5.8. Thanks!
Your HTML has some syntax problem such id=\'myEditor\". I replaced it with id=\'myEditor\' and so ...
Check this jsfiddle
Add angular.min.js and angular-sanitize.min.js to your project. I used jquery 2.2.4 for this sample.
HTML:
<div ng-app="myApp">
<div ng-controller="myCtrl">
<h2>{{html}}</h2>
<span>{{greeting}}</span>
<div ng-bind-html="editorHtml"></div>
</div>
</div>
JS:
var myApp = angular.module('myApp', ['ngSanitize']);
var data = "\r\n\r\n<div id=\"myEditor\" name=\"myEditor\">\r\n\r\n\t\thi html\r\n\t</div>\r\n\r\n\r\n\r\n\r\t";
var script = "<script type=\"text/javascript\"> alert('hi script');\r\n\r\n\t</" + "script>\r\n\t";
myApp.controller('myCtrl', ['$sce', '$scope' , function($sce, $scope) {
$scope.html = data + script;
$scope.editorHtml = $sce.trustAsHtml($scope.html);
$scope.greeting = 'Hola!';
}]);
You have to include jQuery for this to work. Also don't forget ngSanitize.
Plunker
http://plnkr.co/edit/zEXXCB459Tp25VJiyyZb?p=preview

String is not rendering as html in angularJs using $sce

I'm getting the following data from server <span>text</span>.
I'm using the following function in my controller
$scope.getHtml = function (html) {
return $sce.trustAsHtml(html);
};
and in the html as follows
<div class="col-sm-12 col-md-12" ng-bind-html="getHtml(vm.profileData.htmltext)">
After doing this I am getting this in view, it is not rendering :
<span>text</span>
Please tell me where I'm getting things wrong? Thanks in advance
as i mention you need a html entity decode
$scope.html = angular.element('<div></div>').html('<i>text</i>').text();
$scope.getHtml = function() {
return $sce.trustAsHtml($scope.html);
};
plunker url
I recommend this code for this.
function htmlDecode(str) {
return $('<textarea />').html(str).text();
}
// angular js
$sce.trustAsHtml(htmlDecode(html));

AngularJs Return HTML from Controller

I try to return some HTML code from my AngularJs controller to the html data.
This is path of my html :
<div align="right">
{{chooseHtmlElement()}}">
</div>
And this is path of my AngularJs Controller:
$scope.chooseHtmlElement= function () {
var sum = $scope.chiQuadSum();
if (isNaN(sum)) {
return "";
}
if (sum > 17.00) {
return "<i class=\"fa fa-minus-circle\" style=\"color:red;\"></i>";
} else if (sum < 14.00) {
return "<i class=\"fa fa-check-circle\" style=\"color:green;\"></i>";
} else {
return "<i class=\"fa fa-circle\" style=\"color:orange;\"></i>";
}
}
The problem is when I return these string, the element is not shown as html element, but as text which you can read. Is there any possibility returning these string as html element?
While binding html on view in angular js you need to use ng-bind-html directive. But before binding html, you need to sanitize that html by using $sce.trustAsHtml method of ngSanitize module.
<div align="right" ng-bind-html="chooseHtmlElement() | trustedhtml"></div>
Filter
app.filter('trustedhtml',
function($sce) {
return $sce.trustAsHtml;
}
);
you can use
ngSanitize
There are 2 steps:
include the angular-sanitize.min.js resource, i.e.:
<script src="lib/angular/angular-sanitize.min.js"></script>
In a js file (controller or usually app.js), include ngSanitize, i.e.:
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'ngSanitize'])
$refrence
Instead of returning element from controller to HTML use $element to add/append content from controller to HTML. Find your DIV element using angular.element.
var tag = your return elements.
var ele = $compile(tag)($scope);
angular.element('div').append(ele);
For Sanitizing an html string
, Include following module and js in your code,
<script src="//code.angularjs.org/1.4.7/angular-sanitize.js"></script>
angular.module('app', [
'ngSanitize'
]);
Bind scope like,
<div align="right" ng-bind-html="chooseHtmlElement()"></div>

Categories

Resources