Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Add auto-update functionality to Restangular (only for, model.get and model.remove in this example)
angular.module('', [
.factory('RestangularAutoUpdate', function RestangularAutoUpdate(Restangular) {
// properties
var _routes = [];
// helper
// TODO: setParentList needed for
function setParentList(restangularizedElement, collection) {
return Restangular.restangularizeElement(
// auto-update
Restangular.setOnElemRestangularized(function(elem, isCollection, route) {
// only add auto-update to registered routes
if (!_.contains(_routes, route)) { return elem; }
if (isCollection) {
// auto-update on = _.wrap(, function(post, elementToPost, queryParams, headers) {
return post(elementToPost, queryParams, headers).then(function(response) {
// TODO: setParentList needed for
elem.push(setParentList(response, elem));
return elem;
} else {
// auto-update on model.get
elem.get = _.wrap(elem.get, function(get, queryParams, headers) {
return get(queryParams, headers).then(function(response) {
if (elem.getParentList) {
var parentList = elem.getParentList();
// TODO: setParentList needed for
parentList[parentList.indexOf(elem)] = setParentList(response, parentList);
return elem;
// auto-update on model.remove
elem.remove = _.wrap(elem.remove, function(remove, queryParams, headers) {
return remove(queryParams, headers).then(function(response) {
if (elem.getParentList) {
var parentList = elem.getParentList();
parentList.splice(parentList.indexOf(elem), 1);
return elem;
return elem;
// methods
function addRoute(route) {
// service
return {
addRoute: addRoute

This comment has been minimized.

Copy link

commented Jul 9, 2014

Thank you for sharing this! I've been struggling with this for a few days and this solution (modified a bit) is a neat workaround.

One thought: if i do a I expect the new element as return value not the collection (e.g. I'd like to highlight the new element or do something with it (in my case I need the new element because saving to the server assigns the new ID and I have to know that ID) so I've changed line 37-38 to

var tmp = setParentList(response, elem);
return elem[elem.indexOf(tmp)];

Your mileage may vary but for me it seems more practical.
(I'm not good enough in JS to know if return tmp would return the same object reference as
elem[elem.indexOf(tmp)] but this works for me now until mgonto fixes the issue permanently.)

Anyway...thanks again for sharing, really saved me some headache :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.