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 : valuepairs. Therefore the HTML is created in the controller and now we looking to display it.
We have created a model property, but cannot render this in the view without it just printing the HTML.
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 :
Example view :
For Angular 1.x, use ng-bind-html in the HTML:
At this point we would get a attempting to use an unsafe value in a safe context error so we need to either use ngSanitize or $sce to resolve that.
Use $sce.trustAsHtml() in the controller to convert the html string.
There are 2 steps:
Include the angular-sanitize.min.js resource, i.e.:
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 we found solution for this:
Here's the set up:
Fortunately, we 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 we to include markup in a string from a controller, directive, etc:
Finally, in a template, it must be output like so:
We have tried today, the only way we found was this