RuiFortes
RuiFortes

Reputation: 183

How to clean html from angular directives and helper comments?

Is there a way to transform the angular "live DOM" to a flattened plain html? I mean turning this:

<!-- ngRepeat: ref in refs track by $index -->
<p ng_repeat="ref in refs track by $index" class="ng-scope ng-binding">a0120</p>
<p ng_repeat="ref in refs track by $index" class="ng-scope ng-binding">a0241</p>
<p ng_repeat="ref in refs track by $index" class="ng-scope ng-binding">z1242</p>
<p ng_repeat="ref in refs track by $index" class="ng-scope ng-binding">a0120</p>

into this:

<p>a0120</p>
<p>a0241</p>
<p>z1242</p>
<p>a0120</p>

Of course, classes and attributes not related to angular compile process would be kept.

Thanks

Thanks

Upvotes: 0

Views: 1295

Answers (3)

RuiFortes
RuiFortes

Reputation: 183

A guess the best way is to just traverse the DOM

Here's the code I'm using if someone want's to use it, improve it or change it completly...

The attr and class lists are obviously not complete.

function cleanAngularStuff(el) { //recursive function

    var remClassList = ['ng-scope', 'ng-model', 'ng-binding', 'ng-isolate-scope']
    var remAttrList = ['ng-repeat']

    // If node is a comment just remove it
    if (el.nodeType == 8) {
        el.parentNode.removeChild(el);
    }
    // If its an element remove extra attributes and classes and recurse children
    else if (el.nodeType == 1) {

        // Remove extra classes. If none is left remove class attribute
        for (var i = 0; i < remClassList.length; i++) {
            el.classList.remove(remClassList[i]);
            if (el.classList.length == 0) {
                el.removeAttribute('class')
            }
        }

        // Remove attributes
        for (var h = 0; h < remAttrList.length; h++) {
            el.removeAttribute(remAttrList[h])

        }

        // Recurse children
        for (var i = 0, len = el.childNodes.length; i < len; i++) {
            cleanAngularStuff(el.childNodes[i])
            // If child comment is removed decrease cursor
            if (len > el.childNodes.length) {
                len = el.childNodes.length
                i--
            }
        }

    }
}

Upvotes: 1

TyndieRock
TyndieRock

Reputation: 996

I'm not sure exactly what you are trying to do, but if its for SEO purposes with a single page web app you may want to check out this article

http://www.yearofmoo.com/2012/11/angularjs-and-seo.html

Upvotes: 0

Monty Wild
Monty Wild

Reputation: 3991

You can't parse HTML or XML similar documents with regular expressions. Have a look at this discussion: RegEx match open tags except XHTML self-contained tags

You'd be better off using a HTML/XML editor.

Upvotes: 0

Related Questions