这是一个显示问题的方法:http://jsfiddle.net/yRLKe/5/
在注入DOM之前编译一个按钮,另一个按钮在编译之前注入。我做了两件事,以确保我编译的方式不是导致问题的原因。
无论您点击哪个按钮,请检查控制台输出,当您从DOM中选择时,您会看到实际模板的内容不可用。
所以问题首先是为什么? - 为什么它会这样? 但最重要的是? - 如何通过DOM选择器访问实际加载的模板的HTML?
这是模板:
<script type="text/ng-template" id="template1.html">
<div>This is template 1!</div>
<div id="test">Hello {{name}}</div>
</script>
这是控制器:
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');
};
});
这是指令:
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());
});
}
});
该指令输出&#34; test1&#34;到控制台,我希望它输出&#34; Hello Superman!&#34;。
答案 0 :(得分:1)
将输出写入控制台时不会呈现dom。使用$timeout
,您可以查看呈现的内容。很多人说这是一个黑客。无论如何,它的确有效。这是我改变的内容,在两个指令中都有相同的结果:
//after injecting $timeout in the directive:
$compile(container)(scope);
console.log('before');
console.log($('#template').children().text());
$timeout(function(){
console.log('before, in timeout:');
console.log($('#template').children().text());
},0)
另外,see this answer并查看其中的链接。
答案 1 :(得分:0)
您的compileBeforeInsert
肯定无法使用,因为您正在调用编译 - &gt;链接 - &gt;元素但对返回的元素不执行任何操作。这是一个无操作。
至于为什么compileAfterInsert
不起作用,我相信ng-include始终是异步的,即使内容已经在本地可用。这就是为什么rgill的setTimeout
有效。
你可能想重新考虑这种方法...... Angular的想法是它不断地编译和消化,直到事情最终以稳定的最终状态结束。并且可能是该路径中的异步中断。