Skip to content

Commit

Permalink
fix(copy) Collections are now copied/cloned properly
Browse files Browse the repository at this point in the history
Collection elementTransformers didn't get triggered earlier, as restangularizeElem was used for both elements and collections. Now restangularizeCollection is used when copying collections.
  • Loading branch information
bostrom committed Jan 5, 2017
1 parent fb242ae commit c92b138
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
29 changes: 25 additions & 4 deletions src/restangular.js
Original file line number Diff line number Diff line change
Expand Up @@ -996,10 +996,31 @@
elem[config.restangularFields.doGETLIST] = elem[config.restangularFields.customGETLIST];
}

function copyRestangularizedElement(fromElement, toElement) {
var copiedElement = angular.copy(fromElement, toElement);
return restangularizeElem(fromElement[config.restangularFields.parentResource],
copiedElement, fromElement[config.restangularFields.route], fromElement[config.restangularFields.fromServer]);
function copyRestangularizedElement(element) {
var copiedElement = angular.copy(element);

// check if we're dealing with a collection (i.e. an array)
// and restangularize the element using the proper restangularizer,
// element / collection
if (_.isArray(element)) {
return restangularizeCollection(
element[config.restangularFields.parentResource],
copiedElement,
element[config.restangularFields.route],
element[config.restangularFields.fromServer],
element[config.restangularFields.reqParams]
);
}

// not a collection, restangularize it as an element
return restangularizeElem(
element[config.restangularFields.parentResource],
copiedElement,
element[config.restangularFields.route],
element[config.restangularFields.fromServer],
element[config.restangularFields.restangularCollection],
element[config.restangularFields.reqParams]
);
}

function restangularizeElem(parent, element, route, fromServer, collection, reqParams) {
Expand Down
18 changes: 18 additions & 0 deletions test/restangularSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1105,6 +1105,24 @@ describe('Restangular', function() {
$httpBackend.flush();
});

it('should work with cloned collections', function () {
var responseHandler = jasmine.createSpy();

Restangular.addElementTransformer(/^accounts/, true, function(collection) {
collection.customThing = 'customValue';
return collection;
});

Restangular.all('accounts').getList().then(responseHandler);
$httpBackend.flush();

var accounts = responseHandler.calls[0].args[0];
var accountsCopy = accounts.clone();

expect(accounts.customThing).toEqual('customValue');
expect(accountsCopy.customThing).toEqual('customValue');
});

it('should allow for a custom method to be placed at the model level using regexp route when one model is requested', function() {
var accountPromise;

Expand Down

0 comments on commit c92b138

Please sign in to comment.