Search code examples
javascriptangularjsangularjs-scope

Pass angularJs variable to javascript Variable


I have Angularjs variable that I want to pass in javascript variable. I found solution here so it didn't work. My code :

<script>
var demo=angular.module('demo', []);
demo.controller('metrics', function($scope, $http) {
$http.get('http://localhost:8080/metrics').then(function(response) 
    {
     $scope.metrics = response.data;            
    });
    });
</script>

<div ng-controller="metrics">
<p>{{metrics}}<p>
</div>
<script>
var e = angular.element(document.querySelector('[ng-controller="metrics"]')); 
var e1 = e.scope().metrics ; 
alert(e1)   
</script>

I got result from {{metrics}} but e1 didn't return something.
Thanks for your help.


Solution

  • From your current code, by the time the JS code executes, it will not contain metrics data.

    The JS code should be written in the then response of the API call,

    If you do that, the JS code will be called after the metrics gets a value.

    var demo=angular.module('demo', []);
    demo.controller('metrics', function($scope, $http) {
       $http.get('http://localhost:8080/metrics').then(function(response) 
        {
           $scope.metrics = response.data;            
           var e = angular.element(document.querySelector('[ng-controller="metrics"]')); 
           var e1 = e.scope().metrics ; 
           alert(e1);
        });
    });