I add AngularJS 1.x to the form for editing orders (the ability to change the date, delivery and address in this example). I have a Ruby on Rails JSON API with several 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 mine 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 removes the API endpoint, but the parameters are incorrect. I need to find a way to convert between these formats:
{ date: "...", shipping: { ... }, address: { ... } }
{ date: "...", shipping_id: 1, address_attributes: { ... } }
What is the recommended way to do this in AngularJS? Is this something that needs to be done through interceptors? Should I create a new resource Orderand copy the attributes in the desired form order?