简体   繁体   中英

AngularJS - Dynamically add and remove form fields within a table

I wanna add a couple of form fields, dynamically on a button press and all that fields to be in a table (every field to have his own space something like this: <td>field</td>

This is what I have until now and if I put all the code in the table it doesn't work.

HTML

<div ng-app="angularjs-starter" ng-controller="MainCtrl">
   <fieldset  data-ng-repeat="choice in choices">
      <select>
         <option>option 1</option>
         <option>option 2</option>
         <option>option 3</option>
      </select>
      <input type="text" ng-model="choice.name" name="" placeholder="Enter data">
       <input type="text" ng-model="choice.name" name="" placeholder="Enter data 2">
      <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
   </fieldset>
   <button class="addfields" ng-click="addNewChoice()">Add fields</button>
       
   <div id="choicesDisplay">
      {{ choices }}
   </div>
</div>

JS

var app = angular.module('angularjs-starter', []);

  app.controller('MainCtrl', function($scope) {

  $scope.choices = [{id: 'choice1'}, {id: 'choice2'}];
  
  $scope.addNewChoice = function() {
    var newItemNo = $scope.choices.length+1;
    $scope.choices.push({'id':'choice'+newItemNo});
  };
    
  $scope.removeChoice = function() {
    var lastItem = $scope.choices.length-1;
    $scope.choices.splice(lastItem);
  };
  
});

Here is a link to JSFiddle: https://jsfiddle.net/rnnb32rm/1014/

I added table data to your example and i think it works fine?

The only thing you really have to do is replace your fieldset with a tr node and then wrap your inputs in td nodes - and wrap the whole thing in a table node ofcourse.

https://jsfiddle.net/9tk0qpng/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM