Contrary to popular belief, $compile is not actually asynchronous. It is important to use $timeout in your code because of the way browsers handle JavaScript and the manipulation of the DOM. By utilizing $timeout, you allow the DOM to properly update before retrieving the necessary HTML content using .html().
Your implementation correctly incorporates both $compile and $timeout.
Here are a few key points to consider:
$timeout already provides a promise that resolves with the return value of the specified function. So, you can simplify your code like this:
return $timeout(function(){
return linked.html();
});
In your current setup, the top-level element of your template may be getting discarded because .html() returns only the innerHTML. If you want to maintain the root element, consider wrapping it in a div first, as demonstrated below:
return $timeout(function(){
return angular.element('<div/>').append(linked).html();
});
For a complete example, follow the structure below:
var $scope = angular.extend($rootScope.$new(true), data);
var template = angular.element($templateCache.get(templateName));
$compile(template)($scope);
return $timeout(function(){
return angular.element('<div/>').append(template).html();
});