Skip to content

Instantly share code, notes, and snippets.

@DaftMonk
Last active January 2, 2016 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DaftMonk/8265815 to your computer and use it in GitHub Desktop.
Save DaftMonk/8265815 to your computer and use it in GitHub Desktop.
Example for sharing server models with the client
// On the server we setup routes to interface with a car controller
app.post('/api/cars/', car.create);
app.put('/api/cars/:id', car.update);
app.get('/api/cars/:id', car.show);
//-----------------------------------
// To interface with this from the client we'll use angular $resource
/**
* Define our Car $resource class.
* $resource has default methods for: save, get, query, delete
*/
var Car = $resource('api/cars/:id',
{
id: '@id'
},
{
update: { // we'll add an update method since $resource doesn't include one
method: 'PUT'
}
});
/**
* Create a new $resource object and bind it to our form
* example data it gets from the server: { id: 1, name: 'nissan X80', price: 12000 }
*/
$scope.car = Car.get({id: 1}, function() {
/**
* Assume in the view the client increases the cars price
* e.g $scope.car.price = 15000;
*/
/**
* Client submits his changes and triggers update
*/
$scope.update = function() {
// Do some validation
if(isValid($scope.car) {
$scope.car.$update(); // This will PUT { id: 1, name: 'nissan X80', price: 15000 } to /api/cars/1
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment