Search code examples
javascriptangularjsngresource

angularjs ngResource success undefined


I have an ngResource factory like so:

app.service 'Api', ['$resource', ($resource) ->
    {
        Student: $resource "/api/v1/students/:id", {id: "@id", option: "@option"}, { 'update': {method: 'PUT'}}
]

I have a controller like so:

app.controller 'newStudentCtrl', ($scope, $state, Api) ->

    $scope.addNewStudent = ->
        student = Api.Student.save(
            student: $scope.newStudent
            )
        console.log(student.id)
        $state.go('student.new', { id: student.id})

The new Student record is saved, but student.id is returning undefined.

console.log(student) is returning the following:

Resource {student: Object, $promise: Promise, $resolved: false....
$promise: Promise
$resolved: true
id: 88
last_name: "Baggins"

How do I handle the success callback to get the student.id?


Solution

  • This worked for me:

    $scope.addNewStudent = -> 
    Api.Student.save { student: $scope.newStudent}, ((successResponse, headers) ->
        console.log successResponse.id
         ....
    

    The solution was given here:

    handle error callback on save() method $ngResource