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

Posted . Visible to the public.

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.

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);
Arne Hartherz
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2014-04-29 08:00)