Angularjs 无dom编译角度指令模板

Angularjs 无dom编译角度指令模板,angularjs,angularjs-directive,Angularjs,Angularjs Directive,是否可以在没有dom的情况下获得已编译的angular指令html代码 这就是我想要的: var scope = { list: ["Peter","Paul","Mary"] }, template = '<ul><li ng-repeat="item in list"{{item}}</li><ul>', result; result = desiredFunction( scope, template );

是否可以在没有dom的情况下获得已编译的angular指令html代码

这就是我想要的:

var scope = {
        list: ["Peter","Paul","Mary"]
    },
    template = '<ul><li ng-repeat="item in list"{{item}}</li><ul>',
    result;

result = desiredFunction( scope, template );

// result should be: "<ul><li>Peter</li><li>Paul</li><li>Mary</li></ul>"
编辑3:

根据Zervagl的评论,这也是可能的,甚至更短:

    $scope.list = ["Peter", "Paul", "Mary"];
    var template = '<ul><li ng-repeat="item in list">{{item}}</li></ul>';
    var result = $compile(template)($scope)[0];
    $timeout( function() {
        console.log( result );
    });

您可以在DOM中不包含元素的情况下进行编译

假设您进行了适当的注射,您可以:

var template = '<ul><li ng-repeat="item in list"{{item}}</li><ul>';
var jqElem = angular.element("<div>").html(template);
$compile(jqElem)($scope);
附言

您可以将模板直接传递到$compile函数中,但请注意.html将返回内部html,因此您可能需要执行以下操作以获取完整模板:

return $timeout(function(){ return jqElem[0].outerHTML; }, 0);

您可以在DOM中不包含元素的情况下进行编译

假设您进行了适当的注射,您可以:

var template = '<ul><li ng-repeat="item in list"{{item}}</li><ul>';
var jqElem = angular.element("<div>").html(template);
$compile(jqElem)($scope);
附言

您可以将模板直接传递到$compile函数中,但请注意.html将返回内部html,因此您可能需要执行以下操作以获取完整模板:

return $timeout(function(){ return jqElem[0].outerHTML; }, 0);

如果不需要指令解释: 使用$interpolate。然后不需要$compile和$scope。相关的:


如果不需要指令解释: 使用$interpolate。然后不需要$compile和$scope。相关的:


在link函数中,您可以只返回element.html,不是吗?我遗漏了什么吗?@NewDev请查看我的编辑。在链接函数中,您只需返回element.html,否?我遗漏了什么吗?@NewDev请查看我的编辑。您可以将模板直接传递给$compile。@zeroflagL如果我直接传递模板,则应从何处获取已编译字符串$compile返回不同的结果…@heinob result=$compiletemplate$scope。html@zeroflagL,@heinob,这个解决方案有一些问题!html返回未编译的模板。我会给出答案来处理它。没关系-我现在知道你也用$timeout处理了:你可以直接将模板传递给$compile。@zeroflagL如果我直接传递模板,我应该从哪里获得编译后的字符串$compile返回不同的结果…@heinob result=$compiletemplate$scope。html@zeroflagL,@heinob,这个解决方案有一些问题!html返回未编译的模板。我会给出答案来处理它。没关系-现在我知道你也用$timeout来处理它了:
var html = '<div> {{item}} </div>' // or $templateCache.get('myTemplate.html') too
var vars = { item: 'John' };
var result = $interpolate(html)(vars);
// result = '<div> John </div>'