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

fix(input): detect changes in array when its values are changed #2553

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
32 changes: 27 additions & 5 deletions src/ng/directive/input.js
Original file line number Diff line number Diff line change
Expand Up @@ -1006,6 +1006,29 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
$element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
};

var ctrl = this;

function outOfSyncWithModel(value) {
if (ctrl.$modelValue !== value) {
return true;
}
if (isArray(value)) {
return !equals(ctrl.$modelArrayValues, value);
}
return false;
}

function storeArrayValues(value) {
ctrl.$modelArrayValues = [].concat(value);
}

function storeValue(value) {
ctrl.$modelValue = value;
if (isArray(value)) {
storeArrayValues(value);
}
}

/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setViewValue
Expand Down Expand Up @@ -1039,7 +1062,7 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
});

if (this.$modelValue !== value) {
this.$modelValue = value;
storeValue(value);
ngModelSet($scope, value);
forEach(this.$viewChangeListeners, function(listener) {
try {
Expand All @@ -1052,18 +1075,17 @@ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$
};

// model -> value
var ctrl = this;

$scope.$watch(function ngModelWatch() {
var value = ngModelGet($scope);

// if scope model value and ngModel value are out of sync
if (ctrl.$modelValue !== value) {
if (outOfSyncWithModel(value)) {

var formatters = ctrl.$formatters,
idx = formatters.length;

ctrl.$modelValue = value;
storeValue(value);

while(idx--) {
value = formatters[idx](value);
}
Expand Down
14 changes: 14 additions & 0 deletions test/ng/directive/inputSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -990,6 +990,20 @@ describe('input', function() {
});


it("should detect changes in the values of an array", function () {
var list = ['x', 'y', 'z'];
compileInput('<input type="text" ng-model="list" ng-list />');
scope.$apply(function() {
scope.list = list;
});
expect(inputElm.val()).toBe('x, y, z');
scope.$apply(function() {
list.unshift('w');
});
expect(inputElm.val()).toBe('w, x, y, z');
});


xit('should require at least one item', function() {
compileInput('<input type="text" ng-model="list" ng-list required />');

Expand Down