【发布时间】:2017-11-13 13:10:57
【问题描述】:
我正在编写一个函数,该函数可以从 HTML 模板和给出的一些信息创建电子邮件模板。为此,我使用了 Angular 的 $compile 函数。
似乎只有一个问题我无法解决。该模板包含一个基本模板,其中包含无限数量的ng-include。当我使用“最佳实践”$timeout (advised here) 删除所有ng-include 时,它会起作用。所以这不是我想要的。
$timeout 示例:
return this.$http.get(templatePath)
.then((response) => {
let template = response.data;
let scope = this.$rootScope.$new();
angular.extend(scope, processScope);
let generatedTemplate = this.$compile(jQuery(template))(scope);
return this.$timeout(() => {
return generatedTemplate[0].innerHTML;
});
})
.catch((exception) => {
this.logger.error(
TemplateParser.getOnderdeel(process),
"Email template creation",
(<Error>exception).message
);
return null;
});
当我开始将ng-include's 添加到模板中时,此函数开始返回尚未完全编译的模板(一个解决方法是嵌套$timeout 函数)。我相信这是因为ng-include 的异步性质。
工作代码
此代码在完成渲染后返回 html 模板(现在可以重用函数,see this question for the problem)。但是这个解决方案是一个很大的问题,因为它使用 angular private $$phase 来检查是否有任何正在进行的$digest。所以我想知道是否还有其他解决方案?
return this.$http.get(templatePath)
.then((response) => {
let template = response.data;
let scope = this.$rootScope.$new();
angular.extend(scope, processScope);
let generatedTemplate = this.$compile(jQuery(template))(scope);
let waitForRenderAndPrint = () => {
if (scope.$$phase || this.$http.pendingRequests.length) {
return this.$timeout(waitForRenderAndPrint);
} else {
return generatedTemplate[0].innerHTML;
}
};
return waitForRenderAndPrint();
})
.catch((exception) => {
this.logger.error(
TemplateParser.getOnderdeel(process),
"Email template creation",
(<Error>exception).message
);
return null;
});
我想要什么
我希望有一个功能可以处理无限数量的ng-inlude,并且仅在成功创建模板后返回。我没有渲染这个模板,需要返回完全编译的模板。
解决方案
在尝试了@estus answer之后,我终于找到了另一种检查 $compile 何时完成的方法。这导致了下面的代码。我使用$q.defer() 的原因是模板在事件中被解析。因此,我不能像正常的承诺那样返回结果(我不能这样做return scope.$on())。这段代码唯一的问题是它严重依赖ng-include。如果您为函数提供没有ng-include 的模板,则$q.defer 永远不会被解析。
/**
* Using the $compile function, this function generates a full HTML page based on the given process and template
* It does this by binding the given process to the template $scope and uses $compile to generate a HTML page
* @param {Process} process - The data that can bind to the template
* @param {string} templatePath - The location of the template that should be used
* @param {boolean} [useCtrlCall=true] - Whether or not the process should be a sub part of a $ctrl object. If the template is used
* for more then only an email template this could be the case (EXAMPLE: $ctrl.<process name>.timestamp)
* @return {IPromise<string>} A full HTML page
*/
public parseHTMLTemplate(process: Process, templatePath: string, useCtrlCall = true): ng.IPromise<string> {
let scope = this.$rootScope.$new(); //Do NOT use angular.extend. This breaks the events
if (useCtrlCall) {
const controller = "$ctrl"; //Create scope object | Most templates are called with $ctrl.<process name>
scope[controller] = {};
scope[controller][process.__className.toLowerCase()] = process;
} else {
scope[process.__className.toLowerCase()] = process;
}
let defer = this.$q.defer(); //use defer since events cannot be returned as promises
this.$http.get(templatePath)
.then((response) => {
let template = response.data;
let includeCounts = {};
let generatedTemplate = this.$compile(jQuery(template))(scope); //Compile the template
scope.$on('$includeContentRequested', (e, currentTemplateUrl) => {
includeCounts[currentTemplateUrl] = includeCounts[currentTemplateUrl] || 0;
includeCounts[currentTemplateUrl]++; //On request add "template is loading" indicator
});
scope.$on('$includeContentLoaded', (e, currentTemplateUrl) => {
includeCounts[currentTemplateUrl]--; //On load remove the "template is loading" indicator
//Wait for the Angular bindings to be resolved
this.$timeout(() => {
let totalCount = Object.keys(includeCounts) //Count the number of templates that are still loading/requested
.map(templateUrl => includeCounts[templateUrl])
.reduce((counts, count) => counts + count);
if (!totalCount) { //If no requests are left the template compiling is done.
defer.resolve(generatedTemplate.html());
}
});
});
})
.catch((exception) => {
defer.reject(exception);
});
return defer.promise;
}
【问题讨论】:
标签: javascript angularjs typescript asynchronous