Reputation: 61
I have a directive which renders a view template and some js code in my main page which tries to get some element in my view template. And since the js code is executed before the template rendered, the will always be undefined error like
<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>'
}
});
I am not very familiar with angular and your help will be appreciated. Thanks
Upvotes: 1
Views: 1279
Reputation: 6963
Put your code in JavaScript function attach() and call attach() function from Link function in your directive
<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>
Directive Code:
angular.module('myApp', []).directive('test', function(){
return {
restrict: 'E',
template: '<div id="testdiv">Hello</div>',
link: function(scope, elm, attrs, ctrl) {
attach()
}
}
});
Upvotes: 1