0

The variable $scope.compdata i am not able to access outside the controller. Thanks in advance.

  var compdata;
  $scope.fetchCompanies = function() {
   var deferred = $q.defer();
   Company.get({
      arg1 : 'list',
      arg2 : 14
    }, function(success) {
      $scope.compdata = success.data;
      deferred.resolve(success.data); //Edited here
    });
    return deferred.promise;
  };

  $scope.fetchCompanies()
    .then(function(data) { // and this block
      $scope.compdata = data; //Added
      console.log("outside : ",  $scope.compdata) //success
    });

console.log("outside : ",  $scope.compdata); //undefined
Bhavani
  • 41
  • 7
  • 1
    This is because of async execution. The value will be undefined outside resolve of the promise – Vivz Jul 31 '17 at 09:21
  • @bhavani you WILL NOT get access to the data `$scope.compdata` outside as you are setting it inside the async call i.e. ajax call. What Exactly you want to do by accessing `$scope.compdata` outside ? kindly explain the scenario. – user1608841 Jul 31 '17 at 10:04

1 Answers1

0

try with below : declare the compdata variable as -

$scope.compdata = '';
Ganesh
  • 52
  • 6
  • Thanks, Already tried but its not working. – Bhavani Jul 31 '17 at 09:43
  • okay... then try to assign the existing variable into your controller, and call as - var compdata ; is global variable so compdata = $scope.compdata; console.log("outside : ", compdata); – Ganesh Jul 31 '17 at 09:49
  • @Ganesh later console.log will get called immediately as soon as controller get instantiated , which will be again undefined as service promise is not resolved yet – user1608841 Jul 31 '17 at 10:06
  • yes again its undefined – Bhavani Jul 31 '17 at 10:10
  • I mean to say - $scope.fetchCompanies() .then(function(data) { $scope.compdata = data; compdata = $scope.compdata; }); console.log("outside : ", $scope.compdata); – Ganesh Jul 31 '17 at 10:41