manish
manish

Reputation: 21

Angular js - Not updating the modal value after asynchronous call $scope.users

app.controller('tableController', function ($scope, $filter, ngTableParams,$http){

    $scope.users = [];

    $http.get("getjsondata").success(function (response) {
        $scope.users = response;  //ajax request to fetch data into $scope.data
    });

    console.log($scope.users); // I am not getting the updated value as
                               //  I need to pass this value in another function
}); 

Upvotes: 1

Views: 66

Answers (4)

iggymoran
iggymoran

Reputation: 4089

The console.log statement gets executed right after you issue the Http Request.

You need to log it/interact with it in your success callback.

$http.get("getjsondata").success(function (response) {
    $scope.users = response; 
    console.log($scope.users);
});

Also, try not to use $scope in your controllers. See John Papa's style guide for Angular.js

Upvotes: 1

sam1188
sam1188

Reputation: 99

The reason is that console.log($scope.users); will be called before $http.get().success() gets executed;

$http.get() returns a promise.

you can debug this like that:

$http.get("getjsondata").success(function (response) {
    console.log('i am after the promise return')
    $scope.users = response;  //ajax request to fetch data into $scope.data
});
console.log('i get executed first');
console.log($scope.users); 

Upvotes: 1

PeterS
PeterS

Reputation: 2954

Your log message is written outside of the success promise and there is probably being executed before your assignment. Try the following:

$scope.users = [];


$http.get("getjsondata").success(function (response) {
    $scope.users = response;  
    console.log($scope.users); 
});

Don't forget promises are asynchronous and as such will mean they get executed later than whatever is coming after the console.log statement.

Upvotes: 1

Martin Glennon-Brown
Martin Glennon-Brown

Reputation: 291

the success function is a callback after the call is complete if you want to see the value you must call any other functions or pass any values inside the callback

like

$scope.users = [];
$http.get("getjsondata").success(function (response) {
    $scope.users = response; 
    console.log($scope.users);  
});

Upvotes: 3

Related Questions