AngularJS: one "partial form" for creating and updating an article

Let's take a simple form with one text input as an example. I want this partially so I can add other inputs to it and have one form to create and update the artist.

Partial

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

      

Form of creation

<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>

      

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 executor:

$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 artist name:

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

      

The problem is when I create an artist it this.name

is undefined. If I change the data-ng model in parial to data-ng-model="name"

, I can create the artist correctly, but the input is not populated with the name in the update form.

Any ideas on how to properly merge the two shapes in one piece?

+3


source to share


2 answers


The value is actually stored in the artistForm object in the scope.

You just need to change:

name: this.name 

      



to

name: $scope.artistForm.name.$viewValue

      

PS: console.log ($ scope) helps a lot in investigation

+2


source


As I can see, in case of creation, you did not add the artist object to the area. U need to add artist to $ scope. And in the partial u the artist.name should be used.



0


source







All Articles