Posted about 7 years ago. Visible to the public.

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

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

The README suggests 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:

Copy
$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:

Copy
var index = element.indexOf(subElement); if (index > -1) element.splice(index, 1);

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
about 7 years ago
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more