Search code examples
javascriptangularjsangularjs-scopeglobal-variableslocal-variables

Angularjs - How to set value of Global variable according to one of the response data element


I want to set the value of glovalvar according to defined in function hello I am getting response data & according to that I want to set globalvar Value. Here is snippet:

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  var globalvar;
  $scope.globalvar='';
  $scope.hello = function()
  {
    //here I want to set the value of glovalvar.I am getting response              data & according to that I want to set globalvar Value.
      //For an example I am creating this funtion.
    //How can I achieve this.
    //I tries below code:
    $scope.globalvar="ee";
  }
  console.log($scope.globalvar)
});
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

    </head>
  <body ng-app="myApp" ng-controller="myCtrl">
    {{globalvar}}
    </body>
  </html>


Solution

  • You should call the function $scope.hello() before console.log($scope.globalvar)

    var app = angular.module("myApp", []);
    app.controller("myCtrl", function($scope) {
      var globalvar;
      $scope.globalvar='';
      $scope.hello = function()
      {
        //here I want to set the value of glovalvar.
        //How can I achieve this.
        //I tries below code:
        $scope.globalvar="ee";
      }
      $scope.hello()
      console.log($scope.globalvar)
    });