【问题标题】:Compile angular directive template without dom编译没有 dom 的 Angular 指令模板
【发布时间】:2014-10-29 20:54:26
【问题描述】:

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

这就是我想要的:

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>"

有没有可能得到desiredFunction?

编辑:

为了让我的愿望更清楚一点:我想“编译”一个角度指令模板字符串不必将指令推送到 dom 中,因为我不想将它放在大教堂。反正我什至不想要一个指令。我只想要从模板字符串(template-string + scope-object ==> html-string)编译的字符串。

是否有任何 Angular 内部甚至外部(库)方式来做到这一点?

编辑(2):

接受 NewDev 的回答,更正我的 html 模板并添加 $timeout 导致我得到以下解决方案,该解决方案有效:

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

编辑(3):

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

    $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 );
    });

【问题讨论】:

  • 在链接函数中,你可以直接返回element.html(),不是吗?我错过了什么吗?
  • @NewDev 查看我的编辑。

标签: angularjs angularjs-directive


【解决方案1】:

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

假设你有正确的注射,你可以这样做:

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

不过,此时innerHTML 仍未编译。为此,我们需要等到 $digest 循环结束。我知道如何做到这一点的一种方法是使用 $timeout,但这意味着您的函数必须返回一个承诺

return $timeout(function(){ return jqElem.html(); }, 0);

附言

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

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

【讨论】:

  • 您可以将template直接传递给$compile。
  • @zeroflagL 如果我直接传递模板,我应该从哪里获得编译后的字符串? $compile 返回不同的东西...
  • @heinob result = $compile(template)($scope).html()
  • @zeroflagL, @heinob,这个解决方案有一些问题! .html() 返回未编译的模板。我会修改答案来处理。
  • 没关系 - 我现在看到你也用 $timeout 处理了它:)
【解决方案2】:

如果不需要指令解释: 使用$interpolate。那么就不需要$compile 和$scope。相关:Compile a template without passing scope

var html = '<div> {{item}} </div>' // or $templateCache.get('myTemplate.html') too
var vars = { item: 'John' };
var result = $interpolate(html)(vars);
// result = '<div> John </div>'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多