是否可以将角度模板编译为最终的html字符串?

Rui*_*tes 6 html javascript angularjs

是否可以编译此html模板字符串:

"<p>List of products from {{supplier.name}}</p>
<p ng-repeat="ref in refs">{{ref}}</p>"
Run Code Online (Sandbox Code Playgroud)

直接到一个html字符串,如:

"<p>List of products from Some Supplier</p>
<p>a0120</p>
<p>a0241</p>
<p>z1242</p>
<p>z3412</p>"
Run Code Online (Sandbox Code Playgroud)

或至少不太干净的版本:

"<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>"
Run Code Online (Sandbox Code Playgroud)

我尝试使用$ 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);
                    }
            )
        }
    }
})
Run Code Online (Sandbox Code Playgroud)

有什么方法可以直接从模板中获取最终的HTML吗?谢谢

PS:我在这里想要实现的是直接在CKEditor中编辑模板(在文本模式下,而不是源代码),并且最终只能在源模式下添加一些"ng-repeat"属性.使用像Handlebars这样的模板引擎需要在html元素之外的占位符,并且由CKEditor自动删除,因为它只处理html.

可能的解决方案(hacky):一种可能的方法是在隐藏元素上使用compile指令,并在控制器上加载视图后读取元素的内容:

$scope.$on('$viewContentLoaded', $scope.onLoaded);
$timeout(function() {
    var el =$("#text div")[0]
    cleanAngularStuff(el)
    $scope.currMailTemplate.processed = el.innerHTML
});
Run Code Online (Sandbox Code Playgroud)

cleanAngularStuff函数只是为了清理额外的角度指令和类.

如果有人想要使用它或改进它,我会在这里发布.

没有向页面添加元素的任何更好的方法吗?

小智 0

可以通过为您的指令提供模板来完成,如下所示。

app.directive('compile', function($compile) {
return{
    restrict: 'A',
    template: '<p>List of products from {{supplier.name}}</p>
               <p ng-repeat="ref in refs">{{ref}}</p>'
    scope: {
     refs: '='
     supplier: '='
    },
    link: function(scope, element, attrs) {
       # Your code goes here 
    }
}
Run Code Online (Sandbox Code Playgroud)

})