如何从angular指令和帮助器注释中清除html?

时间:2013-10-15 00:44:51

标签: regex dom angularjs

有没有办法将角度“live DOM”转换为扁平的纯HTML? 我的意思是转过来:

<!-- 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>

进入这个:

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

当然,将保留与角度编译过程无关的类和属性。

由于

由于

3 个答案:

答案 0 :(得分:1)

猜测最好的方法就是遍历DOM

以下是我正在使用的代码,如果有人想要使用它,改进它或完全改变它......

attr和class列表显然不完整。

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--
            }
        }

    }
}

答案 1 :(得分:0)

您无法使用正则表达式解析HTML或XML类似文档。看一下这个讨论:RegEx match open tags except XHTML self-contained tags

最好使用HTML / XML编辑器。

答案 2 :(得分:0)

我不确定你到底想要做什么,但如果它用于单页网页应用的搜索引擎优化,你可能想查看这篇文章

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