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>
I have tried today, the only way I found was this
<div ng-bind-html-unsafe="expression"></div>
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:
And this is the HTML:
Good luck.
there is one more solution for this problem using creating new attribute or directives in angular.
product-specs.html
app.js
index.html
or
or
https://docs.angularjs.org/guide/directive
Another solution, very similar to blrbr's except using a scoped attribute is:
And then
Note you may replace
element.append()
withelement.replaceWith()
As of Angular 4, this is the way that now works:
Taken from this question here.
Working example with pipe to display html in template with Angular 4.
1.Crated Pipe escape-html.pipe.ts
`
` 2. Register pipe to app.module.ts
Use in your template
getDivHtml() { //can return html as per requirement}
Please add appropriate implementation for getDivHtml in associated component.ts file.