Here's a jsfiddle showing the problem: http://jsfiddle.net/yRLKe/5/
One button compiles before injecting to the DOM, the other one injects before compiling. I did both to make sure that how I compile wasn't the cause of the problem.
Whichever button you click, check the console output and you'll see that the actual template's contents are not available when selecting from the DOM.
So the question is firstly why? - why does it behave this way? but most importantly how? - how can I get access to the actual loaded template's HTML via DOM selectors?
Here's the template:
<script type="text/ng-template" id="template1.html">
<div>This is template 1!</div>
<div id="test">Hello {{name}}</div>
</script>
Here's the controller:
myApp.controller('MyCtrl', function($scope) {
$scope.name = 'Superhero';
$scope.template = {url:'template1.html'};
$scope.clickButton1 = function(){
$scope.$emit('buttonClicked1');
};
$scope.clickButton2 = function(){
$scope.$emit('buttonClicked2');
};
});
Here's the directive:
myApp.directive('compileBeforeInsert', function($compile){
return function(scope, element, attrs){
scope.$on('buttonClicked1',function(ev){
var container = $('#container');
container.html('<div ng-include src="template.url" id="template">test1</div>');
$compile(container)(scope);
console.log('before');
console.log($('#template').html());
});
}
});
This directive outputs "test1" to the console whereas I would expect it to output "Hello Superman!".