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

fix(ngModel): use $evalAsync for blur events to safely $apply #9808

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions src/ng/directive/input.js
Original file line number Diff line number Diff line change
Expand Up @@ -2416,7 +2416,7 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
</file>
* </example>
*/
var ngModelDirective = function() {
var ngModelDirective = ['$rootScope', function($rootScope) {
return {
restrict: 'A',
require: ['ngModel', '^?form', '^?ngModelOptions'],
Expand Down Expand Up @@ -2460,15 +2460,17 @@ var ngModelDirective = function() {
element.on('blur', function(ev) {
if (modelCtrl.$touched) return;

scope.$apply(function() {
modelCtrl.$setTouched();
});
if ($rootScope.$$phase) {
scope.$evalAsync(modelCtrl.$setTouched);
} else {
scope.$apply(modelCtrl.$setTouched);
}
});
}
};
}
};
};
}];


/**
Expand Down
26 changes: 26 additions & 0 deletions test/ng/directive/inputSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1144,6 +1144,32 @@ describe('ngModel', function() {
dealoc(element);
}));

it('should digest asynchronously on "blur" event if a apply is already in progress',
inject(function($compile, $rootScope) {

var element = $compile('<form name="myForm">' +
'<input name="myControl" ng-model="value" >' +
'</form>')($rootScope);
var inputElm = element.find('input');
var control = $rootScope.myForm.myControl;

$rootScope.$apply(function() {
expect(control.$touched).toBe(false);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a specifc reason why the first two expects are inside the $apply block?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Narretz there is no specific reason for the two expects to be in there. Do you think it would be better to move them just before the apply block? I was just trying to ensure that the touched and untouched state remained exactly the same before and after the blur event.

expect(control.$untouched).toBe(true);

browserTrigger(inputElm, 'blur');

expect(control.$touched).toBe(false);
expect(control.$untouched).toBe(true);
});

expect(control.$touched).toBe(true);
expect(control.$untouched).toBe(false);

dealoc(element);
}));


it('should register/deregister a nested ngModel with parent form when entering or leaving DOM',
inject(function($compile, $rootScope) {

Expand Down