Example of $resource in Angular.js with update and save using a resolver.

I had some issues trying to understand how to use a resolver (for edit view) and $resource to do both a POST (save) and a PUT (update) method call to an API.

Here is an example plurk: http://plnkr.co/edit/KQR1EZPqW0MjLTorCmMr?p=preview

Here is the route, the edit path uses a resolver to pass ‘thing’ object/promise back to the edit.html view before the page loads — this is to prepopulate the form:

Below is the Thing $resource, which provides an easy way to work with a REST interface in Angular. The only trick here is the ‘PUT’ method is not available by default, so you have to add it. Mongo saves ids as ‘_id’ so you have to map ‘id’ to ‘_id’ which is returned from the API.

The Thing controller will handle creating new things:

We inject the ‘Thing’ resource into the controller, and then instantiate a new Thing and save it to the model $scope.newThing.

Below is the new.html view:

The $scope.newThing is referenced and available to the view (ng-model=”newThing.name”).

The tricky part is doing the edit, where we will use a resolver in the route to first get a Thing from the API and inject it into the ThingEditCtrl to pre-populate the model with existing Thing data. This will fetch the data before the page loads.

Hopefully this helps people save time, as I could not find a good working example without reading through several bad examples first.