Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit 5ad4f55

Browse files
committedJan 26, 2019
fix(ngRequired): set error correctly when inside ngRepeat and false by default
Previously, in the required validator, we would read the required setting directly from attr.required, where it is set by ngRequired. However, when the control is inside ngRepeat, ngRequired sets it only after a another digest has passed, which means the initial validation run of ngModel does not include the correct required setting. (Before commit 0637a21 this would not have been a problem, as every observed value change triggered a validation). We now use the initially parsed value from ngRequired in the validator. Fixes #16814 Closes #16820
1 parent 43bb414 commit 5ad4f55

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed
 

‎src/ng/directive/validators.js

+5-5
Original file line numberDiff line numberDiff line change
@@ -68,17 +68,17 @@ var requiredDirective = ['$parse', function($parse) {
6868
require: '?ngModel',
6969
link: function(scope, elm, attr, ctrl) {
7070
if (!ctrl) return;
71-
var oldVal = attr.required || $parse(attr.ngRequired)(scope);
71+
var value = attr.required || $parse(attr.ngRequired)(scope);
7272

7373
attr.required = true; // force truthy in case we are on non input element
7474

7575
ctrl.$validators.required = function(modelValue, viewValue) {
76-
return !attr.required || !ctrl.$isEmpty(viewValue);
76+
return !value || !ctrl.$isEmpty(viewValue);
7777
};
7878

79-
attr.$observe('required', function(val) {
80-
if (oldVal !== val) {
81-
oldVal = val;
79+
attr.$observe('required', function(newVal) {
80+
if (value !== newVal) {
81+
value = newVal;
8282
ctrl.$validate();
8383
}
8484
});

‎test/ng/directive/validatorsSpec.js

+14
Original file line numberDiff line numberDiff line change
@@ -730,5 +730,19 @@ describe('validators', function() {
730730

731731
expect(helper.validationCounter.required).toBe(1);
732732
});
733+
734+
it('should validate once when inside ngRepeat, and set the "required" error when ngRequired is false by default', function() {
735+
$rootScope.isRequired = false;
736+
$rootScope.refs = {};
737+
738+
var elm = helper.compileInput(
739+
'<div ng-repeat="input in [0]">' +
740+
'<input type="text" ng-ref="refs.input" ng-ref-read="ngModel" ng-model="value" ng-required="isRequired" validation-spy="required" />' +
741+
'</div>');
742+
743+
expect(helper.validationCounter.required).toBe(1);
744+
expect($rootScope.refs.input.$error.required).toBeUndefined();
745+
});
746+
733747
});
734748
});

0 commit comments

Comments
 (0)
This repository has been archived.