Search code examples
javascriptangularjsangular-resource

Displaying created record Id in controller of Angularjs


Hi I am writing certain values to database which returns the id of saved record. My factory has following

return {
    postNewR: $resource('/api/newRec', {}, {create: {method: 'POST'}})
}

In my controller I have

newR_factory.postNewR.create(recordData, function(data){
   alert(data.id);
});

Everything works fine. I can see in browser developer tools that in response it is returning id of newly created value i.e 22. However in alert box I get undefined.' Please let me know how i can display the value of id in alert box. Thanks


Solution

  • You have to use the $promise returned like this:

    newR_factory.postNewR.create(recordData).$promise.then(function(data) {
        alert(data.id);
    });
    

    Alternatively, and this is more "angular", you would do it like:

    var new_record = new newR_factory.postNewR(recordData);
    new_record.$save(function(data) {
        alert(data.id);
    });