Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

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

share|improve this answer
    
This behaves differently: toggleOrder is invoked for all orders immediately after they are returned. My goal was to have a button invoke toggleOrder method on the clicked order. –  Nicolas Marchildon Jun 4 at 23:24

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) { ... });
};
share|improve this answer
    
But how can I modify the list once the request is complete? –  Nicolas Marchildon Aug 6 at 14:36

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.