ng-bind-html
If you are up on AngularJS 1.2+ then you might be aware that ng-bind-html-unsafe has been removed. The -unsafe directive was the simple (but unsafe) way to add HTML into your template.
An example went something like:
<p ng-bind-html-unsafe="data.markupData"></p>
Iteration with ng-repeat was also straightforward:
<div ng-repeat="item in items"> <p ng-bind-html-unsafe="item.markupData"></p> </div>
With the
ng-bind-html directive however, there are several more steps involved. Here they are:
1. Create a new controller
var ExampleCtrl = function($scope) { }
And in your HTML:
<div ng-repeat="example in Examples" ng-controller="ExampleCtrl"> <p ng-bind-html="trustedExample"></p> <hr /> </div>
2. Add the
$sce (Strict Contextual Escaping) service to your controller
var ExampleCtrl = function($scope, $sce) { }
3. Use $sce.trustAsHtml function on data
var ExampleCtrl = function($scope, $sce) { $scope.trustedExample = $sce.trustAsHtml($scope.example); }
And that’s it!
Tags: AngularJS, Directives, How To, ng-bind-html, ng-bind-html-unsafe
Thanks! Fast moving framework..
i have small problem with ng-bind-html
i tried to convert escape characters and set that symbol to text box using ng-bind-html . but it is not displaying symbol in text box. is it possible set symbols in text box in angular js. ex: square root symbo
Use ng-model.
Hi!
I think so The best solution is this one:
—– controller or module —
var app = angular.module(‘myapp’, []);
app.controller(‘test’, function($scope){
$scope.data=”hello this is hrml code”
});
app.filter(‘unsafe’, function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
};
});
—html hag–
This tip about ‘Filter’ seems great!
How do I include
$sce
into my project?
Hey there,
You’ll have to add ngSanitize (angular-sanitize.js) file to your project. Then add the module to your project:
angular.module('app', ['ngSanitize']);
Additional tips: https://docs.angularjs.org/api/ngSanitize
how to use angular material using ng-bind-html
Above in my comment HTML got stripped off so rewriting it again, I am stuck in a problem where I am getting HTML like a ng-href=”” and ng-bind-html is converting this to a and stripping off ng-href directive. How to resolve this issue so that ng-bind-html does not strip off angular attributes.
Appreciate your help!!!
Hi there,
Hope you solved the issue! If not, check if you are using $sce.trustAsHtml. Also, if you are looking to add AngularJS-based HTML, consider using a directive.
Some resources:
http://stackoverflow.com/questions/21503588/angularjs-bind-html-string-with-custom-style
http://stackoverflow.com/questions/27348558/why-does-angularjs-strip-out-data-attributes-when-using-ng-bind-html