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:

$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);
Arne Hartherz about 7 years ago
This website uses short-lived cookies to improve usability.
Accept or learn more