Read more

Restangular: How to remove an element from a collection without breaking restangular

Arne Hartherz
April 29, 2014Software engineer at makandra GmbH

So you have a restangular Show archive.org snapshot collection and you want to remove an element from it, after you've successfully deleted it from the server.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

The README suggests Show archive.org snapshot to say something like $scope.users = _.without($scope.users, user). While that works at first glance (the element is no longer in your collection), it will break horribly when you want to use restangular's attributes on that collection.

This is simply because of the way _.without works: It returns a new array with all elements except the removed one. Unfortunately, restangular collections are not plain arrays, but arrays with extra attributes, like route:

$scope.photos.route
// => "photos"
$scope.photos = _.without($scope.photos, photo)
$scope.photos.route
// => undefined

When doing somewhat advanced stuff with restangular, like saving a collection via its parent, you may be doing something like this: element.post(collection.route, collection) (posting to /user/23/photos, for example). That will break after modifying the collection like above.

The following solution works. It uses JavaScript methods which modify the object in place, thus keeping any extra attributes:

var index = element.indexOf(subElement);
if (index > -1) element.splice(index, 1);
Posted by Arne Hartherz to makandra dev (2014-04-29 10:00)