Adding new row of fields with AngularJS ng-repeat

2019-09-08 19:09发布

问题:

I am trying to add a new row of fields after the first row when you click the "Add New Participant" button. I've looked at a few sources and followed suggestions but first of all with this ng-repeat in the code, my fields do not show up. And when I click the "Add New Participant" nothing happens. Not sure what I've got wrong here.

HTML:

<table class="col-md-12" id="client-table">
  <tr>
    <td></td>
    <td>Given Name*</td>
    <td>Middle Name</td>
    <td>Last Name*</td>
    <td>Date of Birth*</td>
    <td>Nationality</td>
    <td>Gender</td>
    <td>Adult or Student</td>
  </tr>
  <tr data-ng-repeat="travelers in traveler">
    <td>1.</td>
    <td>
      <input type="text" placeholder="Given Name" ng-model="travelersForm.givenName"/>
    </td>
    <td>
      <input type="text" placeholder="Middle Name" ng-model="travelersForm.middleName"/>
    </td>
    <td>
      <input type="text" placeholder="Last Name" ng-model="travelersForm.lastName"/>
    </td>
    <td>
      <input type="date" class="date-picker"/>
    </td>
    <td>
      <input type="text" placeholder="Nationality" ng-model="travelersForm.nationality"/>
    </td>
    <td>
      <select name="gender" id="gender" ng-model="travelersForm.gender">
        <option value="male">Male</option>
        <option value="female">Female</option>
      </select>
    </td>
    <td>
      <select name="student" id="student" ng-model="travelersForm.types">
        <option value="student">Student</option>
        <option value="adult">Adult</option>
      </select>
    </td>
  </tr>
  <tr>
    <td>
      <button ng-show="showAddTraveler(traveler)" ng-click="addNewTraveler()">Add New Participant</button>
    </td>
  </tr>
</table>

ANGULARJS

angular.module("travelers", [])
  .controller("travelersController", function($scope) {
    $scope.travelersForm = {};
    $scope.travelersForm.givenName = "Test";
    $scope.travelersForm.middleName = "T";
    $scope.travelersForm.lastName = "Tester";
    $scope.travelersForm.nationality = "White";
    $scope.travelersForm.gender  = "male";
    $scope.travelersForm.types  = "adult";

    $scope.travelers = [];
    $scope.addNewTraveler = function() {
      var newItemNo = $scope.travelers.length+1;
      $scope.travelers.push({'id':'travelers'+newItemNo});
    };
    $scope.showAddTraveler = function(choice) {
      return travelers.id === $scope.travelers[$scope.travelers.length-1].id;
    };
  } );

回答1:

Because your ng-repeat syntax is flipped:

Change:

data-ng-repeat="travelers in traveler">

To:

data-ng-repeat="traveler in travelers">