Using lodash array functions on Restangular collections

Issue

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.

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) { ... });
};

Answered By – blazkovicz

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.