Angular.js Dynamic linking when submitting to server

I am a bit confused about how to achieve two way data binding when submitting to my server.

I have defined my resource like this:

angular.module('todoServices', ['ngResource']).
    factory('Todo', function($resource){
  return $resource('api/v1-0/todos/:todoId', {}, {
    query: {method: 'GET', params:{todoId:''}, isArray: true},
    save: {method: 'POST', isArray: true}
  });
})

      

and I am passing the Todo resource to my controller as a dependency.

Then, in my controller, I have a way to add a new Todo item to my list:

    $scope.addTodo = function() {
        var savedModel = new Todo();
        savedModel.title =  $scope.title;
        savedModel.description = $scope.description,
        //...
        savedModel.$save();
        $scope.todos.push(savedModel);
    }

      

This works until my todo appears in the list, the server call works and the item is added to my database. However, since when I click it into my list, it doesn't have an ID yet. The id is generated by the auto increment id in my MySQL database. My server is returning an object in JSON format, so I'm guessing I have to specify some kind of callback function to get the data binding to work? What exactly do I need to do so my added todo is updated with the correct id as soon as my server returns data?

+3


source to share


1 answer


Just assign the returned object to the saved Model object. Since resource calls are asynchronous and return a promise, you should use the success function like this:

 savedModel.$save(
     function success(savedModel) {
         $scope.todos.push(savedModel);
     });

      



By the way, check the isArray property of the save method, it should usually be false.

+4


source







All Articles