简体   繁体   English

AngularJS:ng-bind-html删除样式

[英]AngularJS: ng-bind-html remove styling

In my app I'm using a table and ng-repeat . 在我的应用程序中,我正在使用tableng-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? 渲染html是否真实,但没有渲染样式和CSS风格? And how? 如何?

like: 喜欢:

<div>123</div>

I believe what you are saying is that article.Content actually contains HTML, and that Angular is stripping out all of the HTML tags. 我相信你所说的是article.Content实际上包含HTML,而Angular正在剥离所有的HTML标签。

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'. 您的代码接近于获得您想要的内容,但您需要使用$ sce服务将内容中的HTML标记为“安全”。 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. .replace()函数从内容中删除任何class="whatever" ,我认为这就是你想要的。

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.) (您需要将app.部分过滤器定义更改为适用于您的应用程序的任何内容。使用您用于.controller()调用的任何前缀/方法。)

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: 然后你将你的data-ng-bind-html="article.Content"更改为:

<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. 我为另一个答案做的Plunk显示了如何使用trustAsHtml过滤器,并展示了如何在控制器中使用$ sce服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM