ng-bind-html

  • June 11th, 2014

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: , , , ,

10 responses to “ng-bind-html”

  1. chi says:

    Thanks! Fast moving framework..

  2. raju says:

    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

  3. 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–

  4. Halivudestevez says:

    How do I include

    $sce

    into my project?

  5. Lani says:

    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!!!

Leave a Reply

Your email address will not be published. Required fields are marked *