Search code examples
angularjsangular-resource

Saving subresource with Angular's $resource


I have a factory defined which returns a $resource:

myApp.factory('Region', function($resource) {
    return $resource(baseUrl + '/templates/:templateId/regions/:regionId', null, {
        query: {
            method: 'GET',
            isArray: false
        },
        update: {
            method: 'PUT'
        }
    });
});

As you can see, a region is a subresource of a template, and I've defined the endpoint as /templates/:templateId/regions/:regionId.

My issue comes when I want to save a new region. How do I specify the templateId to save the region to? Here's my snippet:

$scope.save = function() {
    if ($scope.mode === 'edit') {
        // TODO
    } else {
        Region.save($scope.region, function(success) {
            $state.go('app.templateList')
        });
    }
};

In every other resource I have I've just used Model.save($scope.model);, I don't know how to specify other URL parameters and the Angular docs don't seem to cover it.


Solution

  • According the docs, non-GET (e.g. PUT) methods accepts following arguments

    Resource.save([parameters], postData, [success], [error]).
    

    Where parameters is a path params and it is optional, postData – body of the request. If you want to provide templateId, just add it as first argument:

    Region.save({templateId: 'id'}, $scope.region, function(success) {
        $state.go('app.templateList')
    });