0

Im having an issue with the $scope.items=data when calling success. I am using this jsfiddle : http://jsfiddle.net/SAWsA/11/ However instead of hardcoded items I did this:

   $scope.items=$http({method: 'GET', url: '/test/database/two'}).
   success(function(data, status, headers, config) {
   return data;
   }).
   error(function(data, status, headers, config) {
   $scope.status=status;
   });

and tried this:

$http({method: 'GET', url: '/test/database/two'}).
success(function(data, status, headers, config) {
$scope.items=data;
}).
error(function(data, status, headers, config) {
$scope.status=status;
});

When I put an alert within the success function I see the lenght being 25, so I know i am getting the data. However when I check the $scope.items after this $http run, I get a lengh of undefined after I leave the success function. Like it sets itself and loses it set outside of scope? Any help much appreciated.

2
  • try wrapping the call to $http() inside a $scope.$apply() Commented Oct 14, 2013 at 20:33
  • I did this: $scope.apply($scope.items=$http({method: 'GET', url: 'chj-ld-mgmt066:3000/test/datatables/two'}). success(function(data, status, headers, config) { return data; }). error(function(data, status, headers, config) { $scope.status=status; })); Once I did that I received: TypeError: Object #<Object> has no method 'apply' This is being done within function ctrlRead Commented Oct 15, 2013 at 7:57

1 Answer 1

4

When $http runs it will immediately return either [] or {} depending on whether isArray is set or not. The functions you pass to success or error are executed at a later time, when the data is received. When this data is received the [] or {} you had earlier will be populated with the data.

It sounds like you are running $http and testing for the data before it has had chance to be retrieved from the server. If you want to use the data then your relevant code should probably be inside the success function to defer the work until you have the data you want to work with..

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

2 Comments

Thank you for the explanation that really help me understand what is going on. As well as the answer, that did worked by the way.
Glad you cracked it. If you feel this answer was the solution please mark it as so by clicking the large tick on the left. This will help to keep focus on other unanswered questions.

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.