Search code examples
javascriptangularjsangularjs-scopeangular-http

AngularJs $scope like a local var


i have some issue.

app.controller('groupConfigCntrl', ['$http', '$scope', '$routeParams', function($http, $scope, $routeParams){

            var id = $routeParams.id,
                info = {};
            $http.post("/g/getGroup/", {id: id}).success(function(data) {
              $scope.info = data;
            });
              console.log($scope.info); 
    });

In this case $scope.info is undefined.

        $http.post("/g/getGroup/", {id: id}).success(function(data) {
          $scope.info = data;
          console.log($scope.info); 
        });

In this case, $scope.info - have some data. Why $scope behave like a local var? Help, it's doesn't work when i try to bind data in views. But in similar controller it works.

Controller what works:

app.controller('groupCntrl', ['$http', '$scope', '$uibModal', '$routeParams', '$location', function($http, $scope, $uibModal, $routeParams, $location){
    var id = $routeParams.id;
    $http.post("/g/getGroup/", {id: id}).success(function(data) {
      $scope.info = data;
    });
})

Solution

  • The variable $scope.info is defined inside the success callback after the $http post is complete.

    $http.post("/g/getGroup/", {id: id}).success(function(data) {
                  $scope.info = data;
                  console.log($scope.info); 
                });
    

    You cannot access $scope.info as it is undefined before the $http call.