简体   繁体   中英

Angular JS : Dynamically adding and removing rows in html

I have been trying to implement a page on HTML which integrates with Angular JS, basically to add/remove rows dynamically in a table. I have used the splice function to remove a row. There are 3 issues which I'm facing.

  1. When I add a new row after deleting the last row, it gets populated with recently removed data.

  2. If I remove the 2nd last row and add a new row again, the new row gets populated with the previous last row's data. Also, when I try to edit the row, both the last and 2nd last row's value gets changed simultaneously.

  3. If I add blank rows and remove them using splice, they still remain in the array because when I submit the data to DB, I can see blank records.

I'm quite new to Angular. So, any help is appreciated.

HTML :

<div class="form-group" ng-repeat="item in details track by $index">
  <div class="col-md-3">
    <select class="form-control" ng-model="DetailsName[item.id]" required>
                                            <option>Dropdown 1</option>
                                            <option>Dropdown 2</option>                                             
                                        </select>
  </div>
  <div class="col-md-7">
    <input type="text" class="form-control" ng-model="Details[item.id]" required>
  </div>
  <div class="col-md-1 ">
    <button class="remove " ng-show="!$first " ng-click="removeDetails($index) ">-</button>
  </div>
</div>
<button type="button " class="btn " ng-click="addDetail() ">Add Detail</button>
</div>

JS :

$scope.details = [{id:'detail1'}];
$scope.addDetail = function(){
    var newItemNo = $scope.details.length+1;
    $scope.details.push({'id':'detail'+newItemNo}); 
};

$scope.removeDetails = function (index) {
    $scope.details.splice(index,1);
  };

I think the problem has to do with the way you're generating IDs.

var newItemNo = $scope.details.length+1;

You start with one item. Its ID is detail1 . Adding an item creates detail2 . Adding another creates detail3 .

Now what happens when you remove detail2 ? You're left with ['detail1', 'detail3' ]. What happens when you add a new item now?

Since the array length is 2, and 2 + 1 = 3, the added item becomes detail3 . You have two detail3 s!

Does that make sense? Oddly enough, I ran across this exact same problem a couple of months ago. And it was also an AngularJS app. (Though it could happen just as easily with any framework.)

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