如何在不导致InProg错误的情况下将AngularJS模板呈现给String?

时间:2014-11-20 09:13:27

标签: javascript angularjs angularjs-scope

我正在尝试编写一个将给定模板和范围呈现为字符串的服务。

这是代码:

utilModule.factory('CompilerService', ['$compile', '$templateCache',
    function ($compile, $templateCache) {
        return {
            renderTemplateToString: function(templateName, scope) {
                var template = $templateCache.get(templateName);
                var linkFn = $compile(template);
                var linkedContent = linkFn(scope);
                scope.$apply();

                return linkedContent.html();
            }
        }
    }]);

当我这样称呼时,我得到了由$ apply()调用引起的角度InProg错误:

https://docs.angularjs.org/error/$rootScope/inprog

我正在调用$ apply(),以便在检索html之前在模板中替换变量。

有关如何在没有InProg错误的情况下实现此目的的任何想法?

1 个答案:

答案 0 :(得分:3)

您有两种选择:

if ( !scope.$$phase )
    scope.$apply();

这是在$ digest循环期间检查代码是否正在执行。

但是,$timeout是首选:

$timeout( function(){
  var template = $templateCache.get(templateName);
                var linkFn = $compile(template);
                var linkedContent = linkFn(scope);
}, 0)

编辑:为了使用场所,您应该这样做:

    renderTemplateToString: function(templateName, scope) {
            var deferred = $q.defer();
            $timeout(function(){
               var template = $templateCache.get(templateName);
               var linkFn = $compile(template);
               var linkedContent = linkFn(scope);
               scope.$apply();
               deferred.resolve( linkedContent.html() );
            }, 0);

            return deferred.promise;
    }

$ timeout在执行

之前等待$digest完成