Question

I'm using Restangular with AngularJS, and I would like to iterate over a collection in a function of the controller, where I need to modify a collection returned by Restangular:

var OrderController = [ '$scope', '$http', 'Restangular',
  function($scope, $http, Restangular) {
    $scope.orders = Restangular.all('orders').getList();
    $scope.toggleOrder = function(order) {
      _.forEach($scope.orders, function(order) {
        console.log(order); // This is not an order!
        order.someProperty = false; // My goal
      });
    });
  }];

I think the problem is that $scope.orders is a promise, not an actual array, so _.forEach tries to iterate on the properties of the promise instead of the objects. I get the same result with angular.forEach.

How can I iterate on Restangular resource collections? I'd like to have access to all collection functions of lodash, such as _.filter, as well.

Was it helpful?

Solution

Restangular.all('orders').getList() - is a promise, not array.

Assign your list using $object:

$scope.orders = Restangular.all('orders').getList().$object;

List will be an empty array until request is complete.

UPDATE full code for question (includes orders modification on request complete)

$scope.orders = [];

function modifyOrders(orders){ ... }

Restangular.all('orders').getList().then(function(orders){
 modifyOrders(orders);
 $scope.orders=orders;
});

$scope.toggleOrders = function(toggledOrder){
 _.forEach($scope.orders, function(order) { ... });
};

OTHER TIPS

Try this :

var OrderController = [ '$scope', '$http', 'Restangular',
  function($scope, $http, Restangular) {

    $scope.toggleOrder = 
        Restangular.all('orders').getList().then(function(orders){
            _.forEach(orders, function(order) {
                console.log(order); // This is not an order!
                order.someProperty = false; // My goal
            });
        });
  }];

After getList() method you get the promise that takes the list in param.

From the docs : https://github.com/mgonto/restangular#using-self-reference-resources

Even if accepted answer resolved the misunderstanding over arrays and promises, a problem remains...

_.forEach is ok but _.filter is not. Lodash strips Restangular collection methods.

Indeed

api.getList().then(function(items) {
  console.log(items.getRestangularUrl);
  items = _.filter(items, function() { return true; });
  console.log(items.getRestangularUrl);
));

results in

log: function() {...}

log: undefined

How to accomplish a filter preserving Restangular methods ?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top