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>
on html
OR
on controller
works also with
$scope.comment.msg = $sce.trustAsHtml(html);
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:
EDIT:
Here's the set up:
JS file:
HTML file:
Use
and
For that, you need to include
angular-sanitize.js
, for example in your html-file withFortunately, 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:
Then, the module must be loaded:
This will allow you to include markup in a string from a controller, directive, etc:
Finally, in a template, it must be output like so:
Which will produce the expected output: 42 is the answer.
ng-bind-html-unsafe
no longer works.This is the shortest way:
Create a filter:
And in your view:
P.S. This method doesn't require you to include the
ngSanitize
module.here is the solution make a filter like this
and apply this as a filter to the ng-bind-html like
and thank to Ruben Decrop