1

I'm trying to use $sanitize to decode characters but I'm running into a dilemma. I need to use the $sanitize service(I can't use ng-bind-html) but I seem to be getting two different outputs when I use $sanitize and ng-bind-html even though they are supposed to produce the same result since ng-bind-html goes through $sanitize.

Plnkr here http://plnkr.co/edit/IZPyVUO5zaTnxiIAzPLe?p=preview

Is there a way to get the value of the ng-bind-html output using the $sanitize service? Am I doing something stupid or is this a limitation of the angular implementation?

1 Answer 1

1

Actually ng-bind-html does not necessarily go through $sanitize. I think ng-bind-html is doing more than $sanitize, as $sanitize would only be one phase of ng-bind-html if it presents (called by $sce).

Accoring to ng-bind-html's source code (bottom @ https://github.com/angular/angular.js/blob/master/src/ng/directive/ngBind.js), it is mainly using $sce for the conversion purpose. Something like this:

var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) {
  return function(scope, element, attr) {
    element.addClass('ng-binding').data('$binding', attr.ngBindHtml);

    var parsed = $parse(attr.ngBindHtml);
    function getStringValue() {
      var value = parsed(scope);
      getStringValue.$$unwatch = parsed.$$unwatch;
      return (value || '').toString();
    }

    scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) {
      element.html($sce.getTrustedHtml(parsed(scope)) || '');
    });
  };
}];

The magic part should be element.html($sce.getTrustedHtml(parsed(scope)) || '');.

Sign up to request clarification or add additional context in comments.

2 Comments

I see the difference now. But the trouble still remains. I dont have access to element and I'm trying to do this in a factory. Is that possible?
@dheerajmanju1 Ah ha, I think I've found the trick... You can put the sanitized html into a DOM element and then retrieve the text from it. Like: angular.element('<div>'+$scope.sanitized+'</div>').text(); would produce exactly the same result as your ng-bind-html.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.