lundi 20 avril 2015

AngularJS: One 'partial form' for both create and update article

Let's take a simple form with one text input as an example. I want it to be in a partial so I can add other inputs to it and have one form for both create and update artist.

The partial

<input name="name" type="text" data-ng-model="artist.name" id="name">

The create form

<section data-ng-controller="ArtistsController">
  <form name="artistForm" class="form-horizontal" data-ng-submit="create()" novalidate>
    <ng-include src="'/modules/artists/views/partials/form-artist.client.view.html'"></ng-include>
  </form>
</section>

The edit (or update) form

<section data-ng-controller="ArtistsController" data-ng-init="findOne()">
  <form name="artistForm" class="form-horizontal" data-ng-submit="update(artistForm.$valid)" novalidate>
    <ng-include src="'/modules/artists/views/partials/form-artist.client.view.html'"></ng-include>
  </form>
</section>

In my client controller, I can create an artist :

$scope.create = function() {
  var artist = new Artists({
    name: this.name
  });
  artist.$save(function(response) {
    //success!
  }, function(errorResponse) {
    $scope.error = errorResponse.data.message;
  });
}

And I can update the name of an artist :

$scope.update = function() {
  var artist = $scope.artist;
  artist.$update(function() {
    //success!
  }, function(errorResponse) {
    $scope.error = errorResponse.data.message;
  });
};

The issue is when I create an artist, this.name is undefined. If I change the data-ng-model in the parial to data-ng-model="name", I can create an artist correctly but the input doesn't get filled with the name in the update form.

Any ideas on how to merge the two forms in one partial correctly?

Aucun commentaire:

Enregistrer un commentaire