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

Feat: parse / format / validation for ngModel collection values #12905

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
63 changes: 36 additions & 27 deletions src/ng/directive/ngList.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,40 +90,49 @@ var ngListDirective = function() {
restrict: 'A',
priority: 100,
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
// We want to control whitespace trimming so we use this convoluted approach
// to access the ngList attribute, which doesn't pre-trim the attribute
var ngList = element.attr(attr.$attr.ngList) || ', ';
var trimValues = attr.ngTrim !== 'false';
var separator = trimValues ? trim(ngList) : ngList;
compile: function() {
return {
pre: function(scope, element, attr, ctrl) {
// Inform the model controller that the model is a collection, so it can use deepWatch
// to detect changes
ctrl.$isCollection = true;
},
post: function(scope, element, attr, ctrl) {
// We want to control whitespace trimming so we use this convoluted approach
// to access the ngList attribute, which doesn't pre-trim the attribute
var ngList = element.attr(attr.$attr.ngList) || ', ';
var trimValues = attr.ngTrim !== 'false';
var separator = trimValues ? trim(ngList) : ngList;

var parse = function(viewValue) {
// If the viewValue is invalid (say required but empty) it will be `undefined`
if (isUndefined(viewValue)) return;
var parse = function(viewValue) {
// If the viewValue is invalid (say required but empty) it will be `undefined`
if (isUndefined(viewValue)) return;

var list = [];
var list = [];

if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trimValues ? trim(value) : value);
});
}
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trimValues ? trim(value) : value);
});
}

return list;
};
return list;
};

ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value)) {
return value.join(ngList);
}
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value)) {
return value.join(ngList);
}

return undefined;
});
return undefined;
});

// Override the standard $isEmpty because an empty array means the input is empty.
ctrl.$isEmpty = function(value) {
return !value || !value.length;
// Override the standard $isEmpty because an empty array means the input is empty.
ctrl.$isEmpty = function(value) {
return !value || !value.length;
};
}
};
}
};
Expand Down
177 changes: 148 additions & 29 deletions src/ng/directive/ngModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,18 @@ var VALID_CLASS = 'ng-valid',

var ngModelMinErr = minErr('ngModel');

function NgModelTransformer(name, transformFn, expectsItem) {
this.name = name;
this.transformFn = transformFn;
this.expectsItem = expectsItem;
}

function NgModelValidator(name, validateFn, expectsItem) {
this.name = name;
this.validateFn = validateFn;
this.expectsItem = expectsItem;
}

/**
* @ngdoc type
* @name ngModel.NgModelController
Expand Down Expand Up @@ -221,6 +233,7 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
this.$$viewValueCollection = undefined; // stores the viewValue as a collection if $isCollection is true
this.$validators = {};
this.$asyncValidators = {};
this.$parsers = [];
Expand All @@ -237,6 +250,7 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
this.$pending = undefined; // keep pending keys here
this.$name = $interpolate($attr.name || '', false)($scope);
this.$$parentForm = nullFormCtrl;
this.$isCollection = false;

var parsedNgModel = $parse($attr.ngModel),
parsedNgModelAssign = parsedNgModel.assign,
Expand Down Expand Up @@ -576,8 +590,9 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$

function processSyncValidators() {
var syncValidatorsValid = true;

forEach(ctrl.$validators, function(validator, name) {
var result = validator(modelValue, viewValue);
var result = processValidator(validator, modelValue, viewValue);
syncValidatorsValid = syncValidatorsValid && result;
setValidity(name, result);
});
Expand All @@ -594,7 +609,7 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
var validatorPromises = [];
var allValid = true;
forEach(ctrl.$asyncValidators, function(validator, name) {
var promise = validator(modelValue, viewValue);
var promise = processValidator(validator, modelValue, viewValue);
if (!isPromiseLike(promise)) {
throw ngModelMinErr("$asyncValidators",
"Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
Expand Down Expand Up @@ -653,6 +668,7 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
return;
}
ctrl.$$lastCommittedViewValue = viewValue;
ctrl.$$viewValueCollection = undefined;

// change to dirty
if (ctrl.$pristine) {
Expand All @@ -661,20 +677,36 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
this.$$parseAndValidate();
};


this.$$parseAndValidate = function() {
var viewValue = ctrl.$$lastCommittedViewValue;
var modelValue = viewValue;
parserValid = isUndefined(modelValue) ? undefined : true;

if (parserValid) {
for (var i = 0; i < ctrl.$parsers.length; i++) {
modelValue = ctrl.$parsers[i](modelValue);
var parser = ctrl.$parsers[i];
var modelValueWasArray = isArray(modelValue);
modelValue = processTransform(modelValue, parser);
if (ctrl.$isCollection && !modelValueWasArray && isArray(modelValue)) {
// Once the first parser creates a collection from the viewValue,
// store this as the viewValue collection
ctrl.$$viewValueCollection = viewValue;
}

if (isUndefined(modelValue)) {
parserValid = false;
break;
}
}
}

if (ctrl.$isCollection && !ctrl.$$viewValueCollection) {
// If no parser has set the viewValueCollection,
// assume that the viewValue is already a collection
ctrl.$$viewValueCollection = viewValue;
}

if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
// ctrl.$modelValue has not been touched yet...
ctrl.$modelValue = ngModelGet($scope);
Expand Down Expand Up @@ -709,7 +741,7 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
};

this.$$writeModelToScope = function() {
ngModelSet($scope, ctrl.$modelValue);
ngModelSet($scope, modelValueGetter(ctrl.$modelValue));
forEach(ctrl.$viewChangeListeners, function(listener) {
try {
listener();
Expand Down Expand Up @@ -806,43 +838,129 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
}
};

// model -> value
// Note: we cannot use a normal scope.$watch as we want to detect the following:
// 1. scope value is 'a'
// 2. user enters 'b'
// 3. ng-change kicks in and reverts scope value to 'a'
// -> scope value did not change since the last digest as
// ng-change executes in apply phase
// 4. view should be changed back to 'a'
$scope.$watch(function ngModelWatch() {
this.$$setupModelWatch = function() {
// model -> value
// Note: we cannot use a normal scope.$watch as we want to detect the following:
// 1. scope value is 'a'
// 2. user enters 'b'
// 3. ng-change kicks in and reverts scope value to 'a'
// -> scope value did not change since the last digest as
// ng-change executes in apply phase
// 4. view should be changed back to 'a'

// options.deepWatch
// options.collection

setModelValueHelpers();
$scope.$watch(ngModelWatch);
};

var modelValueGetter = function modelValueGetter(modelValue) {
return modelValue;
};

var modelValueChanged = function modelValueChanged(newModelValue, currentModelValue) {
return newModelValue !== currentModelValue;
};

/**
* If ngModelOptions deepWatch is true, then the model must be copied after every view / scope
* change, so we can correctly detect changes to it with .equals(). Otherwise, the ctrl.$modelValue
* and the scope value are the same, and we cannot detect differences to them properly
*/
function setModelValueHelpers() {
if (ctrl.$options && ctrl.$options.deepWatch || ctrl.$isCollection) {
modelValueGetter = function modelValueGetter(modelValue) {
return copy(modelValue);
};

modelValueChanged = function modelValueChanged(newModelValue, currentModelValue) {
return !equals(newModelValue, currentModelValue);
};
}
}

function ngModelWatch() {
var modelValue = ngModelGet($scope);

// if scope model value and ngModel value are out of sync
// TODO(perf): why not move this to the action fn?
if (modelValue !== ctrl.$modelValue &&
if (modelValueChanged(modelValue, ctrl.$modelValue) &&
// checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
(ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
) {
ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
parserValid = undefined;
modelToViewAction(modelValue);
}
return modelValue;
}

var formatters = ctrl.$formatters,
idx = formatters.length;
function modelToViewAction(modelValue) {
ctrl.$modelValue = ctrl.$$rawModelValue = modelValueGetter(modelValue);
ctrl.$$viewValueCollection = undefined;
parserValid = undefined;

var viewValue = modelValue;
while (idx--) {
viewValue = formatters[idx](viewValue);
}
if (ctrl.$viewValue !== viewValue) {
ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
ctrl.$render();
var formatters = ctrl.$formatters,
idx = formatters.length;

ctrl.$$runValidators(modelValue, viewValue, noop);

var viewValue = modelValueGetter(modelValue);
while (idx--) {
var formatter = formatters[idx];
viewValue = processTransform(viewValue, formatter);
if (ctrl.$isCollection && isArray(viewValue)) {
ctrl.$$viewValueCollection = viewValue;
}
}
if (ctrl.$viewValue !== viewValue) {
ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
if (ctrl.$isCollection && !ctrl.$$viewValueCollection) {
//No formatter returned a collection or no formatters ran
ctrl.$$viewValueCollection = modelValue;
}

return modelValue;
});
ctrl.$render();
ctrl.$$runValidators(modelValue, viewValue, noop);
}
}

function processTransform(value, transform) {
var result;
var transformFn = transform;
var expectsItem = false;

if (isObject(transform)) {
transformFn = transform.transformFn;
expectsItem = transform.expectsItem;
}

if (ctrl.$isCollection && isArray(value) && expectsItem) {
result = value.map(transformFn);
} else {
result = transformFn(value);
}

return result;
}

function processValidator(validator, modelValue, viewValue) {
var result;
var validateFn = validator;
var expectsItem = false;

if (isObject(validator)) {
validateFn = validator.validateFn;
expectsItem = validator.expectsItem;
}

if (ctrl.$isCollection && isArray(modelValue) && expectsItem) {
result = modelValue.reduce(function (result, value, index) {
return result && validateFn(modelValue[index], ctrl.$$viewValueCollection[index]);
}, true);
} else {
result = validateFn(modelValue, viewValue);
}

return result;
}
}];


Expand Down Expand Up @@ -1032,6 +1150,7 @@ var ngModelDirective = ['$rootScope', function($rootScope) {
formCtrl = ctrls[1] || modelCtrl.$$parentForm;

modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
modelCtrl.$$setupModelWatch();

// notify others, especially parent forms
formCtrl.$addControl(modelCtrl);
Expand Down
4 changes: 4 additions & 0 deletions src/ng/directive/validators.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

/* global NgModelValidator: true */

var requiredDirective = function() {
return {
restrict: 'A',
Expand Down Expand Up @@ -65,6 +67,7 @@ var maxlengthDirective = function() {
maxlength = isNaN(intVal) ? -1 : intVal;
ctrl.$validate();
});

ctrl.$validators.maxlength = function(modelValue, viewValue) {
return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
};
Expand All @@ -84,6 +87,7 @@ var minlengthDirective = function() {
minlength = toInt(value) || 0;
ctrl.$validate();
});

ctrl.$validators.minlength = function(modelValue, viewValue) {
return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
};
Expand Down
15 changes: 15 additions & 0 deletions test/ng/directive/ngChangeSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,19 @@ describe('ngChange', function() {
helper.changeInputValueTo('a');
expect(inputElm.val()).toBe('b');
});


it('should set the view if the model is changed by ngChange', function() {
$rootScope.reset = function() {
$rootScope.value = 'a';
};
$rootScope.value = 'a';
var input = helper.compileInput('<input type="text" ng-change="reset()" ng-model="value">');
var inputController = input.controller('ngModel');

$rootScope.$digest();

helper.changeInputValueTo('b');
expect(input.val()).toBe('a');
});
});
Loading