AngularJS: ng-bind-html remove styling

AngularJS: ng-bind-html remove styling

本文关键字:styling remove ng-bind-html AngularJS      更新时间:2023-09-26

在我的应用程序中,我正在使用tableng-repeat。我正在渲染我的数据,其中一列是在以下的帮助下呈现的:

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

但是如果我有这样的内容,我有一个问题:

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

它打破了我的整个风格(因为页面也有换页功能)。

渲染

html 但没有渲染样式和 css 样式是真的吗?又如何?

喜欢:

<div>123</div>
我相信

你的意思是article.Content实际上包含HTML,并且Angular正在剥离所有HTML标签。

您的代码接近于获得所需的内容,但您需要使用 $sce 服务将包含 HTML 的内容标记为"安全"。 执行此操作的一种简单方法是使用此筛选器。

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

然后使用此过滤器去除类:

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

.replace() 函数从内容中删除任何class="whatever",我认为这就是您想要的。

更新:同样,这可以用来去除任何内联样式:

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

(您需要将筛选器定义的app.部分更改为适用于你的应用的任何部分。 使用用于 .controller() 调用的任何前缀/方法。

如果你有几个样式或类要剥离,你应该选择正则表达式的非贪婪版本,即:

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

然后,您将data-ng-bind-html="article.Content"更改为以下内容:

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

或者,对于类和样式删除:

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

我为另一个答案做的这个 Plunk 展示了如何使用 trustAsHtml 过滤器,并展示了如何在控制器中使用 $sce 服务。