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