Javascript 如何在不引起InProg错误的情况下将AngularJS模板呈现到字符串?
我正在尝试编写一个服务,将给定的模板和范围呈现为字符串 代码如下:Javascript 如何在不引起InProg错误的情况下将AngularJS模板呈现到字符串?,javascript,angularjs,angularjs-scope,Javascript,Angularjs,Angularjs Scope,我正在尝试编写一个服务,将给定的模板和范围呈现为字符串 代码如下: utilModule.factory('CompilerService', ['$compile', '$templateCache', function ($compile, $templateCache) { return { renderTemplateToString: function(templateName, scope) { var
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 err:
我调用$apply(),以便在检索html之前在模板中替换变量
关于如何在不出现InProg错误的情况下实现这一点,您有两个选择:
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
在执行之前完成理想情况下,我希望从此服务返回一个字符串,因此如果我使用超时,我是否需要返回一个通过呈现模板传递的承诺?