Create an html element from string with js - javascript

I am trying to create an html elemnt from string in js.
The string is: "<p class='text-muted'> come and see how good I look </p>".
In the past I did this with php by echo it out and now I build the client side only with angularJS and I have no clue how to do it.
I tried to bind the string to the page but, as expected, it prints the whole string without encode the string to html elemnt..
I tried to look for an answer in the internet and specificly in this community without succuess..
Does it possible, and if so, How?
Thanks in advance

You can use the ng-bind-html directive to bind a string of html to an element. The string should be sanitised first for example by injecting $sceand calling $sce.trustAsHtml() on the string to bind.
Example controller:
app.controller('MainCtrl', function($scope, $sce) {
$scope.template = $sce.trustAsHtml('<p class="text-muted"> come and see how good I look </p>');
});
And in html
<div ng-bind-html="template"></div>
Here's a quick example plunker
You can type in html and click to bind it

You can attach a String definition of html to any DOM Elment using the property 'innerHTML'.
yourDomEl.innerHTML = '<div class="your-class"><a>Link</a></div>';

Related

Angular Interpolation for HTML a tag element

I have an Angular template that is trying to grab a string that is an HTML element, but the string is not being rendered properly.
Angular Html (fyi this is a subitem in a ng-repeat):
<div class="right-column">{{item.map[label]}}</div>
This string is pulled in and essentially will be formatted such as:
" Click Here "
The result with this templating is the exact string being shown in the DOM (with some html entities substituted in).
The resulting element in the DOM looks like:
<div class="right-column ng-binding"><a href="..." target="_blank">Click Here</a></div>
I did notice that if I edit the HTML in the browser dev tools and replace the html entities (&lt and &gt) with the actual characters < and > that the html element is being rendered correctly.
I have tried using [innerHTML]="item.map[label]" in the templating, which results in nothing being rendered. I have also tried ng-bind-html="item.map[label]" which was giving errors even when using ngSanitize in the controller js file.
I am not sure what else to try for a proper fix. If there is a way I can format the string that is passed in without messing with the angular template, that would be preferred since there are other formats that are passed into the template other than just this tag style.
I see there's a typo
" target="_blank"> Click Here "
should be:
" Click Here "
I think binding to [innerHTML] should work, if it doesn't work you can tell angular that the HTML is safe and you by pass the sanitizing process. You achieve it by creating a pipe that apply DomSanitizer's bypassSecurityTrustHtml on the HTML string.
Example slackblitz:
https://stackblitz.com/edit/angular-2baxog
As a reference you read more here
Angular HTML binding

angularjs variable in javascript

This is the first time to use angular js.
The following code gives desired output:
Hello
It opens a page:
http://www.example.com/xyz/cat/
But the below code is not working as expected:
<a href='javascript:void(0)' onClick='javascript:window.open("http://www.example.com/xyz/{{life.animal}}/","Windows","width=1150,height=450,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,titlebar=no,location=no,directories=no,status=no");return false')'>Hello </a>
It opens page:
http://www.example.com/xyz/{{life.animal}}/
I think I am doing some basic mistake but please help me.
The Angular scope is not available outside of Angular, i.e. vanilla JS.
To set a click function the angular way you should use ng-click
Create a function in your controller or directive such as
scope.open = function() {
$window.open(...)
}
In the template do
ng-click="open()"
angular doesn't interact with strings, but you try to do that in your onclick handler that opens a window (you pass a string there). Stop the string and concat with the variable:
onClick='javascript:window.open("http://www.example.com/xyz/" + life.animal)'
Also, as #Enzey has noted, use ng-click instead of onClick, and then bring out the javascript from your html and do that stuff in a controller instead.
E.g.:
HTML
Foo
Controller
$scope.myFunction = function() {
window.open(...whatever...);
}
The double hash are used for angular directives not for Javascript Vanilla apart of that is better if you use ng-href instead href in a <a> tag. You can check this here

Render subscript to HTML from js object

I'm working on an Angular 1X application which has stored all icon labels into a js object like this
var labels={
........
iconlabel_o2:"O<sub>2</sub>",
iconLabel_co2:"CO<sub>2</sub>",
iconLabel_h20:"H<sub>2</sub>O",
........
}
and the iconLabel values are called into HTML
<p>{{u.iconLabel}}</p>
but the values are not getting rendered as subscripts. It just shows the whole string. like this...
O<sub>2</sub>
CO<sub>2</sub>
H<sub>2</sub>O
How to fix this?
You can use the ng-bind-html directive to achieve this:
<p ng-bind-html="u.iconLabel"></p>
Please also have a look at a similar question: AngularJS - Render HTML tags that are contained in a string

Angular character encoding issue contenteditable div

I'm using a combination of Angular and a contenteditable div to try and create a two way binding that I can later use an Angular controller to manipulate the data. Everything has been working great, with the exception of certain html characters that make there way into the model.
For example, when I type & I get & when there is a nonbreaking space I get nbsp;
How do I modify the contenteditable directive to clean the encoded values out and only keep the unencoded versions?
Plunkr here - http://plnkr.co/edit/ToylycanYcMJq15K36Yd?p=preview
You will see in the contenteditable directive I have this line:
html = element.html().replace(' ','');
To try and replace the values, but it's having no affect...
Although you can do something like this, but I think you would be better using input or textarea for the same. According to docs AngularJS Models support only input, select or textarea.
Also there is an open issue for the same problem that you are facing.
Here is the code if you intend to use contenteditable div:
var myApp = angular.module('app',[]);
myApp.controller('chatterCtrl', ['$scope', function($scope) {
$scope.$watch('comment', function(){
if($scope.comment != undefined){
$scope.comment = unescape($scope.comment);
}
}, true);
}]);

How to bind text as a DOM object in Angularjs

I want to show MathML DOM object dynamically with Angularjs.
This is what I wrote:
var mathML = angular.module('mathML', ['ngSanitize']);
mathML.controller('mathMLCtrl', ['$scope', function ($scope) {
$scope.result = function(){
return "<math xmlns='http://www.w3.org/1998/Math/MathML'><msup><msqrt><mrow><mi>a</mi><mo>+</mo><mi>b</mi></mrow></msqrt><mn>27</mn></msup></math>";
//return "<p>p tag</p>";
};
}]);
With ng-bind-html, I can insert text as a HTML text, but MathML's XML is not inserted properly. (All tags are deleted.)
It looks like necessary to insert MathML text as DOM Objects. But I don't know how to do it.
How can I show MathML with Angularjs?
ng-bind-html sanitizes the output by removing tags that are not listed as "safe". The math tag is not listed under the allowed tags. If you trust this html to never have exploits, you'll want to use the $sce service to mark the code as trusted. See this answer:
https://stackoverflow.com/a/19417443/1248889
Another alternative would be to save this text as a partial, in it's own separate file. Then in your html, use ng-include to load the partial into the dom.

Categories