I am encountering a significant issue with form inputs nested within the ng-repeat directive. I require an input that is an array and can vary in size; allowing users to add or remove parts of the form.
Within the ng-repeat directive, there is an ng-form element - my goal is to access the $dirty value of each element in the array. While everything seems to be working fine, there is one hiccup - removing elements does not properly update the FormControllers. Although the ng-repeat effectively removes an element from the view when it's deleted from the model, the ng-form fails to update its position accordingly.
Before removal:
$index = 0, formRepeated.$dirty == true, model.value == 1
$index = 1, formRepeated.$dirty == false, model.value == 2
If I remove element 0 from $scope.model, the following scenario occurs:
$index = 0, FormController $dirty == true, value == 2
The attached FormController fails to update its position, retaining the values of $dirty, $touched, $error, etc.
I have exhausted all my options and seem to be at a standstill. Any suggestions on how to tackle this problem would be greatly appreciated.
Below is the HTML structure:
<div ng-controller="MyController">
<form name="form">
<div ng-repeat="modelPart in model track by $index">
<div ng-form="formRepeated">
<input type="text" ng-model="modelPart.value" name="form_{{$index}}_value">
<button ng-click="$parent.removeFormRepeated($index)">
Remove
</button>
<div>Is dirty: {{ formRepeated.$dirty }}</div>
</div>
</div>
<button ng-click="addNew()">add new</button>
</form>
</div>
Here is the JavaScript code:
var app = angular.module('app', []);
app.controller('MyController', function MyController($scope) {
$scope.model = [{value: 1}, {value: 2}];
$scope.addNew = function() {
$scope.model.push({});
}
$scope.removeFormRepeated = function(index) {
$scope.model.splice(index, 1);
};
});