R. Kumar
R. Kumar

Reputation: 1

How to use value outside http.then in Angular

My code of controller is : -

var app = angular.module('myApp');
app.controller('myCtrl', function() {
    $scope.year = "1350";
    $scope.ord1 = "";
    $scope.s1t1 = function() {
        $http({
            url: 's1t1.json',
            method: 'GET'
        }).then(function(response) {
            $scope.set = response.data;
            //console.log($scope.set);
            $scope.obj = $scope.set.find(o => o.year === $scope.year);
            $scope.ord1 = $scope.obj.ordinal;
        });
    }
    alert($scope.ord1);
});

I get a value like 44144 in $scope.ord1. and I need to use it in my controller outside s1t1 function. I represent It with a alert. I am also try it with $rootScope but result is same.

Upvotes: 0

Views: 166

Answers (3)

Love-Kesh
Love-Kesh

Reputation: 812

Use timeout function

        var app = angular.module('myApp');
        app.controller('myCtrl', function($timeout) {
         $scope.year = "1350";
         $scope.ord1 = "";
         $scope.s1t1 = function() {
            $http({
                url: 's1t1.json',
                method: 'GET'
            }).then(function(response) {
                $scope.set = response.data;
                //console.log($scope.set);
                $scope.obj = $scope.set.find(o => o.year === $scope.year);
                $scope.ord1 = $scope.obj.ordinal;

               // Call a function in timeout
               $timeout(funuction(){
                    myFunctionTousevalue();        
           },100)

            });
         }
          var myFunctionTousevalue = function () {
            alert('Using Value: '+$scope.ord1);
          }
        });

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 76444

Things are not executed sequentially (synchronously) in your code. $http is asynchronous, which means that the function is called, a request is sent but your code will not wait for a response and just after the function call you do not have a value yet. You will need to put your code which depends on the response inside the callback in the then.

Upvotes: 1

Shubhranshu
Shubhranshu

Reputation: 521

alert inside the then function, it will take a small amount of time but you will get a value. Call a function where you want to use the value.

var app = angular.module('myApp');
app.controller('myCtrl', function() {
 $scope.year = "1350";
 $scope.ord1 = "";
 $scope.s1t1 = function() {
    $http({
        url: 's1t1.json',
        method: 'GET'
    }).then(function(response) {
        $scope.set = response.data;
        //console.log($scope.set);
        $scope.obj = $scope.set.find(o => o.year === $scope.year);
        $scope.ord1 = $scope.obj.ordinal;
        alert($scope.ord1);

       // Call a function where you want to use the value
       myFunctionTousevalue();
    });
 }
  var myFunctionTousevalue = function () {
    alert('Using Value: '+$scope.ord1);
  }
});

Upvotes: 0

Related Questions