I'm adding AngularJS 1.x to a form for editing orders (being able to change the date, shipping, and address in this example). I have a Ruby on Rails JSON API with a few endpoints:
GET /addresses
[{ id: 1, line1: "...", line2: "...", zip: "..." }, ...]
GET /shippings
[{ id: 1, name: "priority" }, ...]
GET /orders/:id
{ date: "...",
shipping: { id: 1, name: "priority" },
address: { id: 1, line1: "...", line2: "...", zip: "..." } }
PATCH /orders/:id
{ date: "...",
shipping_id: 1,
address_attributes: { line1: "...", line2: "...", zip: "..." } }
Inside my OrdersController I have the following:
var app = angular.module('app');
app.controller('OrdersController', ['$scope', 'Order', 'Address', 'Shipping',
function($scope, Order, Address, Shipping) {
$scope.order = Order.get({ id: 123 });
$scope.addresses = Address.query();
$scope.shippings = Shipping.query();
$scope.save = function() {
$scope.order.$save(function() {
// ...
}, function(error) { alert(error); });
};
}
]);
My form is pretty simple:
<form ng-submit="save()">
<input type="date" ng-model="order.date" />
<select ng-model="order.shipping"
ng-options="option.name for option in shippings track by option.id">
</select>
<input type="text" ng-model="order.address.line1" />
<input type="text" ng-model="order.address.line2" />
<input type="text" ng-model="order.address.zip" />
<input type="submit" value="Save"/>
</form>
The save function hits my API endpoint - however the parameters are incorrect. I need to find a way to transform the between these formats:
{ date: "...", shipping: { ... }, address: { ... } }
{ date: "...", shipping_id: 1, address_attributes: { ... } }
What is the recommended way of doing this in AngularJS? Is this something that should be done through interceptors? Should I be creating a new Order resource and copying over the attributes in the desired form order?