Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: ng-bind-html remove styling

In my app I'm using a table and ng-repeat. I'm rendering my data, one of columns is rendered with the help of:

<div class="cell" data-ng-bind-html="article.Content">
</div>

But I have a problem, if I have content like:

<div class="page-wrap">123</div>

It breaks my whole style (because page has page-wrap too).

Is it real to render html, but without rendering style and css style? And how?

like:

<div>123</div>
like image 582
brabertaser19 Avatar asked Mar 09 '15 12:03

brabertaser19


1 Answers

I believe what you are saying is that article.Content actually contains HTML, and that Angular is stripping out all of the HTML tags.

Your code is close to getting you what you want, but you need to use the $sce service to mark the content with HTML in it as 'safe'. A simple way to do that is to use this filter.

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

Then use this filter to strip out the classes:

app.filter('stripClasses', function() {
  return function(str) {
    return str.replace(/class=['"].*["']/, '');
  }
});

The .replace() function strips out any class="whatever" from the content, which I think is what you want.

UPDATE: Similarly, this could be used to strip out any inline styles:

app.filter('stripStyles', function() {
  return function(str) {
    return str.replace(/style=['"].*["']/, '');
  }
});

(You need to change the app. part of the filter definitions to whatever works for your app. Use whatever prefix/method you use for your .controller() calls.)

If you have several styles or classes to strip, you should go for the non greedy version of the regex which is:

str.replace(/class=['"](.*?)["']/g, '')

Then you would change your data-ng-bind-html="article.Content" to this:

<div class="cell" data-ng-bind-html="article.Content | stripClasses | trustAsHtml"></div>

Or, for both class and style removal:

<div class="cell" data-ng-bind-html="article.Content | stripStyles | stripClasses | trustAsHtml"></div>

This Plunk I did for another answer shows how you can use the trustAsHtml filter and shows how you use the $sce service inside a controller, as well.

like image 117
Michael Oryl Avatar answered Sep 17 '22 14:09

Michael Oryl