How to remove angularjs attributes and classes from HTML?

I have a simple AngularJS app that renders a parent element containing some nested elements from a template using ng-bind and ng-repeat. I would like to grab the HTML (innerHtml) of the generated element (as a string) for use in another application (where it should be used as static HTML, outside of the AngularJS context).

It's easy to do this using jQuery('#parent-element').html()

. The problem with this approach is that the HTML string contains Angular attributes (like ng-bind) as well as Angular generated comments (from ng-repeat) and classes (like ng-scope).

Maybe I'll come up with some kind of regex to clear everything from the string directly, but I'd be interested to know if there is a cleaner way to do this.

So, is there a "Angular" way to prevent attributes / classes / comments from being generated, or to fetch a clean version of the original HTML of the generated elements?

UPDATE: For @ suhas-united and others who might find this useful, I ended up using the following, which works well enough for my use -

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, " ");

      

+3


source to share


3 answers


need to clear the attrs value and then clear it easily



 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, '')

      

+1


source


If you don't have a very large number of ng attributes, you can try something like this:

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

      



If you have a large number of them, see Get all attributes from HTML element with Javascript / jQuery and you can add the method

div.removeAllAttr("ng-")

      

0


source


I found a soul:

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

      

It clears any "ng-" and "ng-" directives!

0


source







All Articles