0

I face the problem that I get some string from the server that represents an html and I need to parse style attrs for some nodes and then show this html inside the view with Angular.

So I see this answer https://stackoverflow.com/a/494348/1022726 that helps me to create an html node from a string then I go over each item and change styles. In the end I do $sce.trustAsHtml with the value of innerHTML.

I have this code http://plnkr.co/edit/HUfAGR2uNMwb48rqXbkk?p=preview

<div ng-bind-html="trustedHtml"></div>

function($scope, $sce) {
  var s = '<h1 style="color: red; font-size: 16px;">Subheader</h1><p style="font-size: 12px;">text</p>';
  var div = document.createElement('div');
  div.innerHTML = s;

  $(div).find("*").each(function () {
    $(this).height('100px');
  });

  $scope.trustedHtml = $sce.trustAsHtml(div.innerHTML);
}]);

I want to know if there are any better ways to parse a string that represents html and then show that html in the view. Any help is appreciated.

Community
  • 1
  • 1
iurii
  • 4,142
  • 2
  • 23
  • 28

1 Answers1

3

You could make it into a filter, such as

app.filter('trusted', function($sce){
  return function(text) {
    return $sce.trustAsHtml(text);
  };
});

and then in your html you could have

<div ng-bind-html="text | trusted"></div>
Sean
  • 541
  • 7
  • 26
  • thanks for you reply. Do you know if this is a legit usage $sce.trustAsHtml(div.innerHTML) of trustAsHtml method? – iurii Jul 02 '15 at 20:30
  • I don't see why it wouldn't be. Someone correct me if I'm mistaken. – Sean Jul 02 '15 at 22:21