Pregunta

I am using AngularJS and NGResource and I can't figure out why when I use query, I keep getting an empty array back.

In my controller, I am doing

Task = $resource('/tasks'); 
var tasks = Task.query(function () {});
console.log(tasks);
$scope.tasks = tasks;

In the view

{{tasks}}

In the view it displays correctly

[{"created_at":"08/08/2013","created_by_id":2,"description":"description","id":1,"name":"test task 1","parent_task_id":null,"task_type_id":1,"updated_at":"08/08/2013"},
{"created_at":"08/08/2013","created_by_id":2,"description":"description","id":2,"name":"test task 2","task_type_id":1,"updated_at":"08/08/2013"}]

but in the console it gets logged as an empty array:

[]

Also, i'm using batarang extension for chrome and the scope that it shows tasks as having is:

tests: 
  [  ]

I need to perform some data operations on the returned value before I put it into the $scope model. Is this typical behavior and theres something i'm missing? Or am I doing something wrong? Any ideas would be appreciative. I've been stuck on this for too long.

¿Fue útil?

Solución

You're logging the empty array before it's been populated by the asynchronous AJAX result.

Part of Angular's magic is that it'll automatically update the tasks array with the new data as it comes down the wire, and also auto update the view.

As proof, try this:

var Task = $resource('/tasks');

$scope.tasks = Task.query(function () {});;

$scope.$watch('tasks', function (value) {
    console.log(value);
});

Here's a quote from the docs:

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most case one never has to write a callback function for the action methods.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top