0

I am using AngularJs in my application. I make a http call and getting the response. The response contains an array which I am putting as resultinside the $scope object. I am placing a watch on some attribute and try to access the stored object put inside the $scope object. If I print the result object, I see that it contains the array, but when I try to use the array properties such as length it throws an error. I am also not able to use other array methods such as results.data[0].

Please let me know where I am going wrong. Some code for understanding purpose:

var processResponse = function (result) {
          $scope.results = result.data;
      }

$scope.$watch('attribute', function(newVal) {
        console.log($scope.results.length)
      });
2
  • can you show the logs Commented Dec 7, 2015 at 12:57
  • Got it. Since it is a ajax and asynchronous when I tried to print the length, the results was not yet added to the scope. Hence it was throwing Typer error. Commented Dec 7, 2015 at 13:05

3 Answers 3

2

Depend how you call this. If the result is a promisse you can try do it:

result.then(successCallback, errorCallback);

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

1 Comment

I think this is an elegant solution which I will use. thanks
1

Just try to declare/init $scope.results = []; at the top of your controller. Then the method length couldn't crash ;)

Comments

0

Since it was asynchronous request, I had to take care of null by the following code:

if ($scope.results && $scope.results.data){
    console.log($scope.results.data.length);
}

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.