I am writing a function that can create an email template from a HTML template and some information that is given. For this I am using the $compile
function of Angu
I think you get stuck by chain the promise and compile event. I followed the serial of your questions and this maybe what you are looking for, the compiled template string with recursive ng-include.
First, we need to define ourself the function to detect when the compile is completed, there are couple ways to achieve that, but the duration checking is my best bet.
// pass searchNode, this will search the children node by elementPath,
// for every 0.5s, it will do the search again until find the element
function waitUntilElementLoaded(searchNode, elementPath, callBack){
$timeout(function(){
if(searchNode.find(elementPath).length){
callBack(elementPath, $(elementPath));
}else{
waitUntilElementLoaded(searchNode, elementPath, callBack);
}
},500)
}
In below example, directive-one
is the container element to wrap up all of the output template that I need, so you could change it to what-ever element that you like. By using $q of Angular, I will expose the promise function to capture the output template since it works async.
$scope.getOutput = function(templatePath){
var deferred = $q.defer();
$http.get(templatePath).then(function(templateResult){
var templateString = templateResult.data;
var result = $compile(templateString)($scope)
waitUntilElementLoaded($(result), 'directive-one', function() {
var compiledStr = $(result).find('directive-one').eq(0).html();
deferred.resolve(compiledStr);
})
})
return deferred.promise;
}
// usage
$scope.getOutput("template-path.html").then(function(output){
console.log(output)
})
TL;DR; My Demo plunker
In extra, if you are using the TypeScript 2.1, you could use async/await to make the code looks more cleaner instead of using callback. It would be something like
var myOutput = await $scope.getOutput('template-path')