platanus / angular-restmod

Rails inspired REST-API ORM for Angular
http://platanus.github.io/angular-restmod/
MIT License
1.18k stars 87 forks source link

When `$save` fails the item is modified regardless #368

Open vprogramador opened 8 years ago

vprogramador commented 8 years ago

this is the description of the reason for opening this issue

First, I create a restmod model:

app.factory('Negocio', function(restmod) {
  return restmod.model('http://localhost:3000/negocios')
})

Then, I'm resolving a collection for my controller using the model called 'Negocio':

resolve: {
  negocios: ['Negocio',
    function(Negocio){
      return Negocio.$search().$resolve().$asPromise()
    }],
},

and then adding it to the $scope

$scope.negocios = negocios

I'm using this collection for showing all the items using ng-repeat in an index view. In this view I have a button that opens a modal for editing the chosen item. This modal is created with a service provided by ui.bootstrap, and has its own controller, which first resolve the chosen item and then add it to its $scope.

resolve: {
  negocio: function() {
    return utils.encontrarPorId($scope.negocios, negocioId)
  },
}

// in the modal controller
$scope.negocio = negocio

The function called encontrarPorId receives as arguments an array (the collection) and an Id (the one of the chose item) and returns the item of the collection that matches the Id.

In the view associated to the modal controller, I use $scope.negocio in a form for getting the user input, and this form has a submit button that saves the changes:

$scope.negocio.$save()

The problem is that when the users edit the item info using the form, $scope.negocio changes immediately because of the angular data binding, and it doesn't matter if the modal is cancelled (closed) whithout pressing the submit button or if the user click the submit button and the PUT request fail, the item info in the collection gets modified.

Right now I'm resolving the item in the controller making a new request to the API for avoiding this issue

resolve: {
  negocio: function() {
    return $scope.negocios.$find(negocioId).$resolve().$asPromise()
  },
}

But I'll like to resolve the item from the collection without making a new request to the API, because I already have the item info, don't want to bring it again.

Looking for a solution to my problem found the restmod issue #49 and thought it could be related.

Thanks for your help :)