I am working on a somewhat lengthy form that has a section where a block of form fields are dynamically added/removed. So far I have not been able to find a way to make this method work.
For example, if I add 3 subcontractors and fill in the input for each, the ngmodel holds the value as it should. However, if I remove one of the fields the ngmodel is still holding the input value. Additionally, if I remove the 2nd field in the series it doesn't actually remove that instance, it just reduces the count so instead of having field #1 and field #3 like I should, I actually have field #1 and field #2.
The end result in all of this is to submit to the process page and have a loop iterate through the total # of added fields and insert them into a db.
I'm new to angularjs so I'm not sure that the method I am attempting is even best practice as it seems to be overly complex, so I am open to suggestions on how to improve the process as well.
HTML
<div ng-repeat="subcontractor in subcontractors">
<div class="well well-sm">Subcontractor #{{subcontractor.id}}<span id="subCounter"></span>
<button type="button" ng-click="removeSub()" class="close" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="form-group">
<div class="col-md-6">
<label for="subName">Subcontractor Name</label>
<input type="text" class="form-control" id="subName" name="subName" placeholder="Subcontractor" ng-model="formData.subName['subName'+($index+1)]">
</div>
<button type="button" class="btn btn-info btn-sm pull-right" ng-show="showAddSub(subcontractor)" ng-click="addNewSub()">[+] Add New Sub</button>
</div>
ANGULARJS
$scope.addNewSub = function() {
var newItemNo = $scope.subcontractors.length+1;
$scope.subcontractors.push({'id': +newItemNo});
};
$scope.removeSub = function() {
var newItemNo = $scope.subcontractors.length-1;
$scope.subcontractors.splice($scope.subcontractors-1, 1);
};
$scope.showAddSub = function(subcontractor) {
return subcontractor.id === $scope.subcontractors[$scope.subcontractors.length-1].id;
};