是否可以编译这个 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 吗?
谢谢
附:
我在这里想要实现的是直接在 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 https://stackoverflow.com/questions/19371540/how-to-clean-html-from-angular-directives-and-helper-comments/19405732#19405732如果有人想使用它或改进它。
有没有更好的方法来做到这一点而不向页面添加元素?