daniel
daniel

Reputation: 35733

Angular ng-bind-html / sanitize does not work

I added the ngSanitize Module to my app and added the javascript file.

var myApp = angular.module('partApp', ['ngRoute', 'ngSanitize',  ...]

But the html output is only without attributes. For example myhtml = '<span style="font-size:12px">test</span>' does only output the span without the style.

  <div ng-if="show!==undefined" ng-cloak ng-bind-html="myhtml"></div>

Upvotes: 1

Views: 3372

Answers (3)

7xRobin
7xRobin

Reputation: 431

For me was more effective do a filter

angular.module('app.filters', [])
.filter("sanitize", ['$sce', function($sce) {
    return function(htmlCode){
     return $sce.trustAsHtml(htmlCode);
   }
}]);

And in html use:

<div ng-if="show!==undefined" ng-cloak ng-bind-html="myhtml | sanitize"></div>

Upvotes: 1

Jony-Y
Jony-Y

Reputation: 1579

you need to use $sce.trustAsHtml... so ng-bind-html="trustAsHtml()" in html and in controller

$scope.trustAsHtml = function(html){
return $sce.trustAsHtml(html);
}

or better yet create your own $compile directive such as :

app.directive('ngHtmlCompile',function ($compile) {
  return function(scope, element, attrs) {
      scope.$watch(
        function(scope) {
           // watch the 'compile' expression for changes
          return scope.$eval(attrs.ngHtmlCompile);
        },
        function(value) {
          // when the 'compile' expression changes
          // assign it into the current DOM
          element.html(value);

          // compile the new DOM and link it to the current
          // scope.
          // NOTE: we only compile .childNodes so that
          // we don't get into infinite loop compiling ourselves
          $compile(element.contents())(scope);
        }
    );
};

});

and then use it like so :

<span ng-html-compile="html"></span>

EDIT - made minor fix here is a jsfiddle showing the code

Upvotes: 3

Constantine Poltyrev
Constantine Poltyrev

Reputation: 1034

Angular html-binding does not completely trust interpolated expressions. You need to explicitly tell it to trust a particular expression using $sce service (https://docs.angularjs.org/api/ng/service/$sce).

Somewhere in your controller you should have this snippet:

myhtml = $sce.trustAsHtml(myhtml);

Upvotes: 0

Related Questions