我有一个指令,它在我的主页面中呈现一个视图模板和一些js代码,它试图在我的视图模板中获取一些元素。并且由于js代码在呈现模板之前执行,因此将始终是未定义的错误,如
<body ng-app="myApp">
<test></test>
<script src="angular.js"></script>
<script src="directives.js"></script>
<script>
//try to get an element in directive and failed
alert(document.getElementById('testdiv').innerHTML);
</script>
</body>
simple in directive.js
angular.module('myApp', []).directive('test', function(){
return {
restrict: 'E',
template: '<div id="testdiv">Hello</div>'
}
});
我对角度不是很熟悉,你的帮助将不胜感激。谢谢
答案 0 :(得分:1)
将您的代码放在JavaScript函数attach()中,并从Link函数调用attach()函数 在你的指令
<body ng-app="myApp">
<test></test>
<script src="angular.js"></script>
<script src="directives.js"></script>
<script>
//try to get an element in directive and failed
function attach()
{
alert(document.getElementById('testdiv').innerHTML);
}
</script>
</body>
指令代码:
angular.module('myApp', []).directive('test', function(){
return {
restrict: 'E',
template: '<div id="testdiv">Hello</div>',
link: function(scope, elm, attrs, ctrl) {
attach()
}
}
});