我有一个简单的AngularJS应用程序,它使用ng-bind和ng-repeat从模板呈现包含一些嵌套元素的父元素。我想获取生成元素的HTML(innerHtml)(作为字符串),以便在不同的应用程序中使用(在AngularJS的上下文之外,它将用作静态HTML)。
使用jQuery('#parent-element').html()
很容易做到这一点。这种方法的问题是HTML字符串包含Angular属性(例如ng-bind)以及Angular生成的注释(来自ng-repeat)和类(例如ng-scope)。
我可能会想出一些正则表达式直接从字符串中清除所有这些,但我很想知道是否有更简洁的方法来执行此操作。
那么,是否存在更多“Angular”方法来阻止生成属性/类/注释或者提取生成元素的源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, " ");
答案 0 :(得分:1)
需要清除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, '')
答案 1 :(得分:0)
如果你没有非常多的ng-属性,你可以尝试这样的事情:
var div = $("#mydiv");
div.removeAttr("ng-repeat").removeAttr("ng-bind")....
如果您有大量的,请参阅Get all Attributes from a HTML element with Javascript/jQuery,然后您可以添加方法
div.removeAllAttr("ng-")
答案 2 :(得分:0)
我找到了灵魂:
var x = angular.element('#id').html()
.replace(/(ng-\w+-\w+="(.|\n)*?"|ng-\w+="(.|\n)*?"|ng-(\w+-\w+)|ng-(\w+))/g, '')
.replace(/<!--(.*?)-->/gm, "")
它清除任何&#34; ng - &#34;指令和&#34; ng - &#34;类!