【发布时间】:2013-10-16 11:19:24
【问题描述】:
是否可以编译这个html模板字符串:
"<p>List of products from {{supplier.name}}</p>
<p ng-repeat="ref in refs">{{ref}}</p>"
直接到一个html字符串,如:
"<p>List of products from Some Supplier</p>
<p>a0120</p>
<p>a0241</p>
<p>z1242</p>
<p>z3412</p>"
或者至少是不太干净的版本:
"<p class="ng-scope ng-binding">List of product from Duval</p>
<!-- 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">z3412</p>"
我尝试使用 $compile(templateStr)($scope) 但返回的 dom 元素未完全处理。 但是我没有使用以下指令将其编译为页面元素,并检查该元素我可以看到它具有我正在寻找的最终 html:
app.directive('compile', function($compile) {
return{
restrict: 'A',
scope: {
compile: '=compile',
data: '=ngData'
},
link: function(scope, element, attrs) {
scope.$watch('data',
function(value) {
for (var k in scope.data)
scope[k] = scope.data[k];
}
)
scope.$watch('compile',
function(value) {
element.html(value);
var a = $compile(element.contents())(scope);
}
)
}
}
})
有什么方法可以直接从模板中获取最终的 html 吗? 谢谢
PS: 我在这里想要实现的是直接在 CKEditor 中编辑模板(在文本模式下,而不是源代码) 并且最终才进入源模式以添加一些“ng-repeat”属性。 使用像 Handlebars 这样的模板引擎需要 html 元素之外的占位符,并且会被 CKEditor 自动删除,因为它只处理 html。
可能的解决方案(hacky): 一种可能的方法是在隐藏元素上使用编译指令,并在控制器上加载视图后读取元素的内容:
$scope.$on('$viewContentLoaded', $scope.onLoaded); $timeout(function() { var el =$("#text div")[0] cleanAngularStuff(el) $scope.currMailTemplate.processed = el.innerHTML });
cleanAngularStuff 函数只是为了清理额外的角度指令和类。
如果有人想使用或改进它,我会发布 here。
在不向页面添加元素的情况下,有没有更好的方法来做到这一点?
【问题讨论】:
-
我试过了,但我想使用 ckeditor(或类似的)来编辑模板,这些编辑器只允许 html 元素。在元素标签外添加 {{#each ref}} 会自动删除
-
@RuiFortes 这取决于您何时需要编译的内容。你想通过 Angular 的 html 输出来实现什么?
-
刚刚在原帖中添加了一些解释
-
我真的不明白你为什么要在你的范围内绑定到
'compile'...在你的控制器范围内有一些编译对象吗?$scope.data在您的控制器中看起来像什么?我想更多的上下文会有所帮助。 -
@tennisgent compile 是一个指令。请参阅docs.angularjs.org/api/ng.$compile 我只是将其更改为使用隔离范围。我还使用了一些 hacky 策略来提取传递“数据”对象属性到范围根,这样我就不必为所有模板占位符添加前缀
标签: javascript html angularjs