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

feat(ngModel): pass the previous and current model to view change listeners #13151

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
11 changes: 6 additions & 5 deletions src/ng/directive/ngModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,7 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
ctrl.$modelValue = allValid ? modelValue : undefined;

if (ctrl.$modelValue !== prevModelValue) {
ctrl.$$writeModelToScope();
ctrl.$$writeModelToScope(ctrl.$modelValue, prevModelValue);
}
}
});
Expand Down Expand Up @@ -719,16 +719,16 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$

function writeToModelIfNeeded() {
if (ctrl.$modelValue !== prevModelValue) {
ctrl.$$writeModelToScope();
ctrl.$$writeModelToScope(ctrl.$modelValue, prevModelValue);
}
}
};

this.$$writeModelToScope = function() {
this.$$writeModelToScope = function(currentModelValue, previousModelValue) {
ngModelSet($scope, ctrl.$modelValue);
forEach(ctrl.$viewChangeListeners, function(listener) {
try {
listener();
listener(currentModelValue, previousModelValue);
} catch (e) {
$exceptionHandler(e);
}
Expand All @@ -751,7 +751,8 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
* and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
* value sent directly for processing, finally to be applied to `$modelValue` and then the
* **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
* in the `$viewChangeListeners` list, are called.
* in the `$viewChangeListeners` list, are called. The parameters for the $viewChangeListeners are
* the current and the previous value.
*
* In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
* and the `default` trigger is not listed, all those actions will remain pending until one of the
Expand Down
11 changes: 11 additions & 0 deletions test/ng/directive/ngModelSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,17 @@ describe('ngModel', function() {
});


it('should pass the previous view value to the change listener', function() {
ctrl.$setViewValue('val');

var spy = jasmine.createSpy('viewChangeListener');
ctrl.$viewChangeListeners.push(spy);
ctrl.$setViewValue('val2');

expect(spy).toHaveBeenCalledWith('val2', 'val');
});


it('should reset the model when the view is invalid', function() {
ctrl.$setViewValue('aaaa');
expect(ctrl.$modelValue).toBe('aaaa');
Expand Down