如何从HTML中删除angularjs属性和类

How to remove angularjs attributes and classes from HTML?

本文关键字:angularjs 属性 删除 HTML      更新时间:2023-09-26

我有一个简单的AngularJS应用程序,它使用ng bind和ng repeat来渲染包含模板中一些嵌套元素的父元素。我想获取生成元素的HTML(innerHtml)(作为字符串),以便在不同的应用程序中使用(在AngularJS上下文之外,它将作为静态HTML使用)。

使用jQuery('#parent-element').html()可以很容易地做到这一点。这种方法的问题在于HTML字符串包含Angular属性(例如ng-bind)以及Angular生成的注释(来自ng-reeat)和类(例如ng-scope)。

我可能会想出一些正则表达式来直接从字符串中清除所有这些,但我很想知道是否有更干净的方法。

那么,有没有一种更"角度"的方法来阻止生成属性/类/注释,或者提取生成元素的源HTML的干净版本?

更新:对于@suhas united和其他可能觉得这很有用的人来说,我最终使用了以下内容,它对我的用例来说足够好——

var cleaner = angular.element('#dirtier')
            .html()
            .replace(/<!--[^>]*-->/gi, '')
            .replace(/'n/g, '')
            .replace(/ng-.+?'b/g, '')
            .replace(/ng-.+?=".*?"/g, '')
            .replace(/class=""/g, '')
            .replace(/'"/g, "'''"")
            .replace(/'s+/g, " ");

需要清除attrs值,然后很容易清除

 var x = String(a)
    /*replace comments*/    .replace(/<!--(.*?)-->/gm, "")
    /*replace value of attrs*/    .replace(/="(.*?)"/gm, "")
    /*replace html markup */ .replace( /<['s'S]*?>/g, "")
    /*replace whitespaces */  .replace(/'s/g, '')

如果你没有大量的ng-属性,你可以尝试这样的方法:

var div = $("#mydiv");
div.removeAttr("ng-repeat").removeAttr("ng-bind")....

如果您有大量的属性,请参阅使用Javascript/jQuery从HTML元素中获取所有属性,然后您可以添加一个方法

div.removeAllAttr("ng-")

我找到了一个灵魂:

    var x = angular.element('#id').html()
        .replace(/(ng-'w+-'w+="(.|'n)*?"|ng-'w+="(.|'n)*?"|ng-('w+-'w+)|ng-('w+))/g, '')
        .replace(/<!--(.*?)-->/gm, "")

它清除任何"ng-"指令和"ng-"类!