JSFiddle - React, Tailwind, and code Playground
by yingrui
HTML
<div ng-controller="Ctrl">
<form name="form">
<h3 ng-show="form.$valid">
If all the fields are not empty, you can <input type="button" ng-click="save()" value="Save"/>
</h3>
<h3 ng-show="form.$invalid">
You need to fulfill all the fields, otherwise you cannot save.
</h3>
<table style="border: solid 1px">
<thead>
<tr>
<th>Name</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in vm.persons">
<td><input my-required ng-model="person.name"/></td>
<td><a ng-click="deleteALine(person)" href=''>Delete</a></td>
</tr>
</tbody>
</table>
<div style="margin-top: 5px;">
<input type="button" ng-click="addNewLine()" value="Add"/> a new person into this form.
</div>
<p>The problem here is: After you add a new line and delete it, it should be able to save, but indeed it's not.</p>
<p>While $digesting, the form.$valid is actually set to true, but the Save button still hide.<br/> I would like to know if it is a bug or caused by design?</p>
</form>
</div>
JavaScript
var module = angular.module('ngRepeatTest', []);
module.directive('myRequired', [function () {
return {
restrict: "A",
require: ['ngModel', '^form'],
link: function (scope, iElement, iAttrs, ctrls) {
var formCtrl = ctrls[1],
ngModelCtrl = ctrls[0];
iElement.addClass("required");
scope.$watch(function () {
return isValid(ngModelCtrl.$modelValue)
}, function (newValue) {
formCtrl.$setValidity("MYREQUIRED", newValue, ngModelCtrl);
});
}
};
function isValid(value) {
return !!value;
}
}]);
module.controller('Ctrl', ['$scope', function ($scope) {
$scope.vm = {persons: [
{name: 'Jim'}
]};
$scope.addNewLine = function () {
$scope.vm.persons.push({});
};
$scope.deleteALine = function (person) {
for (var index = 0; index < $scope.vm.persons.length; index++) {
if (person.name === $scope.vm.persons[index].name) {
$scope.vm.persons.splice(index, 1);
return;
}
}
};
}]);