Reputation: 3540
I'm using AngularJS's $resource module to sync "Appointments" back and forth with the server. An appointment contains a title, description, and time.
The server accepts new appointments via a JSON object POST'd at api/appointments
, ie.
{
title: "Doctors Visit",
description: "Check up",
time: "1:00pm"
}
Now the server will save the appointment and add an id to the object, and render a JSON response:
{
id: 23,
title: "Doctors Visit",
description: "Check up",
time: "1:00pm"
}
The problem is, if I use the $resource module to save a new Appointment, it doesn't save the id
attribute to the local JS object.
var Appointment = $resource('example.com/api/appointments/:id.json', {id: "@id"}, {
update: {method: "PUT"}
});
var appointment = new Appointment();
appointment.title = "CEO Meeting";
appointment.description = "Meeting with the CEO";
appointment.time = "2:00pm"
appointment.$save()
The appointment
variable doesn't have the attribute id
ever assigned to it, even after the response is finished.
What is the best way to do this?
Upvotes: 0
Views: 285
Reputation: 3540
The issue was that I was passing a new Appointment object into a modal that was binded to a form, like so:
<form name="appointmentForm" ng-submit="saveAppointment(appt)">
...
</form>
The saveAppointment
function wasn't being passed a resource, it was being passed a POJO with the attributes from the form.
I converted that to a $resource object and everything started working:
$scope.saveAppointment = function(appt)
{
appt = new Appointment(appt); //Appointment was made using $resource
}
Upvotes: 0
Reputation: 4176
It likely doesn't save the id on the local variable because the id is likely being created on your server. To retrieve the id of the object you could either alter the response object on the server to include the newly-created object's id or, after creating the object, you could post a GET request to retrieve the id of the object.
Upvotes: 1