我正在写一个函数,可以从HTML模板创建一个电子邮件模板并提供一些信息。为此,我使用Angular的$compile
函数。
只有一个问题,我似乎无法解决。该模板包含一个无限量的基本模板ng-include
's。当我使用'最佳做法'$timeout
(advised here)它适用于我删除所有ng-include
's。所以这不是我想要的。
的$超时例如:
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
的添加到这个功能开始返回尚未完全编译模板(一workarround被嵌套$timeout
功能)的模板。我相信这是因为ng-include
的异步性质。
工作代码
此代码返回,当它完成渲染(功能现在可以重复使用,see this question for the problem)HTML模板。但是这个解决方案是一个很大的问题,因为它使用角度专用的$$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答案后试验,我终于发现,当$编译完成检查的其他方式。这导致了下面的代码。我使用$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;
}
谢谢你的回答。然而,我似乎无法找到将第二种解决方案整合到我的功能中的方法(请参阅我的主题问题)。问题是,当我在创建的作用域对象上设置事件监视时,事件从未触发任何事件。你有一个例子,我应该如何将其整合到我的功能? 哦,你的plunkr不起作用。它不会给我任何html输出。 –
庞克工程。它有'console.log'语句。检查控制台。我不确定你的整合意味着什么。您需要在范围上设置观察者并调用$ compile,就是这样。这里的顺序应该不重要,但是要先设置观察者。考虑提供一个可以重新创建问题的plunk,如果这不适合你。无论如何,ng-include是1.0以来的传统指令,如果可能的话应该避免,因为它不符合当前的Angular最佳实践。 – estus
我刚刚发现,由于我使用$ rootScope。$ new()(我在服务中没有任何范围)事件不会被触发。你知道为什么,如果$ rootScope导致它,你知道任何解决方案吗?请参阅http://plnkr.co/edit/ZEVSG7TBpYirR77UDxcF?p=preview –