Search code examples
angularjsrestangular

Adding newly-created object to Restangular collection


I'm using Restangular with an AngularJS app and starting with a simple CRUD application. The issue I am having is understanding how to add a new item to a pre-existing collection.

Within the controller the pre-existing collection is obtained in the service and made available on the scope:

$scope.data.items = Restangular.all('items');

A new item is created through a form and created on the server:

$scope.data.items.post(newitem);

I'd like to add this new item to the pre-existing collection but not sure how. The restangular sample just calls Restangular.all('items') again, which seems very wasteful given that all of the information is present. Ideally I'd like to do something like this:

$scope.data.items.post(newitem).then(function(response) {
  $scope.data.items.push(newitem);
});

But this does not work. How should I add to the collection rather than just refetch the entire collection each time I create a new item?


Solution

  • It doesn't work because what you're assigning to data.items is a promise.

    If you change it to the following it should work:

    Restangular.all('items').then(function(items) {
        $scope.data.items = items
    });
    

    Hope it works!