Search code examples
javascriptangularjsangular-resource

Server updates with AngularJS


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?


Solution

  • 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
    }