1

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

2
  • 1
    Once you start using AnuglarJS you should avoid running direct JS code. Can you give some more details around your scenario. Once you have created directive why not use it's link function to manipulate DOM Commented Sep 19, 2013 at 4:30
  • Thanks Chandermani! My scenario is that I am converting a 'classic' application into a angularjs based one. I have a jquery based custom.js file having business with dom elements.(handling animation, dom replacing and some other things). Now these dom elements have been put into separate templates and I don't want to change the custom.js file. I want these templates loaded, then call the custom.js Commented Sep 19, 2013 at 6:27

1 Answer 1

1

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()
      }

  }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.