0

I am new to Angular. The following code prints the right user email ("my_email@domain.com") but in the javascript alert it shows "{{user_name}}"instead of "my_email@domain.com".

<div ng-app="app" ng-controller="MyController" id="id123">
{{user_name}}
</div>
<script> var to_print=document.getElementById('id123').innerText; alert(to_print) </script>

Thank you for your help.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Sam Carli
  • 25
  • 4
  • While you already have an answer, my suggestion would be to put the code inside your angular controller, in the angularJs document ready event. See https://stackoverflow.com/a/18646795/7029064 for details – Edwin Chua Dec 18 '19 at 08:08

1 Answers1

0

Javascript code is load before the angular. So, the value of {{username}} is not found. Use SetTimeout to wait for the angular code to load.

<div ng-app="app" ng-controller="MyController" id="id123">
{{user_name}}
</div>
<script> 
setTimeout(function(){
           var to_print=document.getElementById('id123').innerText; 
           alert(to_print)
          }),1000); 
</script>

Hope!!it will be helpful.

  • Hi Vishal, Thank you for your support. when I changed the code as you advised, the issue is still not solved. Now, both the code and the javascript alert show {{user_name}}. – Sam Carli Dec 16 '19 at 07:27
  • I corrected a typo as below but now the alert is not triggered : ``` ``` – Sam Carli Dec 16 '19 at 07:34
  • My bad!! Your solution works. thank you very much. – Sam Carli Dec 16 '19 at 07:46
  • You need to put this code inside the controller to ensure it will be executed after angular completes its initialization. – clayton.carmo Dec 16 '19 at 07:46
  • Surely there must be a better way to know when Angular is initialized than arbitrarily wait an amount of time and hope? – Jamiec Dec 16 '19 at 08:58