0

Im a newbie in AngularJs and do not really know how to get length of response outside function.

  var onUsers = function(response){               
  $scope.users = response.data;      
  console.log($scope.users.length);  //here works
  }

But when i try outside onUsers function

 console.log($scope.users.length);

I get an error.

4
  • Do you get anything with console.log($scope.users)? Commented Mar 22, 2016 at 21:16
  • You're accessing $scope.users before it is assigned the response.data. $http is Promise returning so you need to access the data after the Promise has resolved. Commented Mar 22, 2016 at 21:18
  • @peteb yes thats the solution , thanks ! Commented Mar 22, 2016 at 21:30
  • @Konkko i couldnt get any data with that line too Commented Mar 22, 2016 at 21:31

3 Answers 3

1

I think the problem is that you are trying to access $scope.users.length before your response has returned from the server. so $scope.users is still undefined. This is a classic problem of asynchronous javascript and you need to use promises for this. Which means that you should write the code that you are executing outside onUsers in the promise callback.

Read this: https://docs.angularjs.org/api/ng/service/$q

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, i was trying to get that before response . Thank you for detailed explanation !
1

You can use $scope.$watch for run a function when the variable change.

$scope.$watch('users', function(users) {
    console.log(users.length);
});

1 Comment

Thank you for your answer, i will take it in consideration .
0

AS the angular code runs asynchronous so console.log($scope.users.length) runs before the promise returned.

var onUsers = function(response){               
      $scope.users = response.data;      
      console.log($scope.users.length);  //here works
      }

your console.log($scope.users.length) in above function works because it is a success handler. you can get the your console.log works out side the success handler by using $timeout. i am assuming after 5000 your response will arive.

  $timeout(function() {
    console.log($scope.users.length);
  }, 5000);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.