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

Commit d316b9c

Browse files
committed
feat(input): rename form controls when name is updated
1 parent ba0b169 commit d316b9c

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

src/ng/directive/form.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
*/
55
var nullFormCtrl = {
66
$addControl: noop,
7+
$$renameControl: noop,
78
$removeControl: noop,
89
$setValidity: noop,
910
$$setPending: noop,
@@ -127,6 +128,23 @@ function FormController(element, attrs, $scope, $animate) {
127128
}
128129
};
129130

131+
// Private API: rename a form control
132+
form.$$renameControl = function(control, newName) {
133+
var oldName = control.$name;
134+
135+
if (form[oldName] === control) {
136+
form[newName] = form[oldName];
137+
delete form[oldName];
138+
control.$name = newName;
139+
} else if (controls.indexOf(control) !== -1) {
140+
// The oldName is not the same as this form control, but this form control is in the form
141+
// somewhere... So just update the newName. This potentially creates 2 references to the same
142+
// control.
143+
form[newName] = control;
144+
control.$name = newName;
145+
}
146+
};
147+
130148
/**
131149
* @ngdoc method
132150
* @name form.FormController#$removeControl

src/ng/directive/input.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2387,6 +2387,12 @@ var ngModelDirective = function() {
23872387
// notify others, especially parent forms
23882388
formCtrl.$addControl(modelCtrl);
23892389

2390+
attr.$observe('name', function(newValue) {
2391+
if (modelCtrl.$name !== newValue) {
2392+
formCtrl.$$renameControl(modelCtrl, newValue);
2393+
}
2394+
});
2395+
23902396
scope.$on('$destroy', function() {
23912397
formCtrl.$removeControl(modelCtrl);
23922398
});

test/ng/directive/inputSpec.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1317,6 +1317,19 @@ describe('input', function() {
13171317
});
13181318

13191319

1320+
it('should rename form controls in form when interpolated name changes', function() {
1321+
scope.nameID = "A";
1322+
compileInput('<input type="text" ng-model="name" name="name{{nameID}}" />');
1323+
expect(scope.form.nameA.$name).toBe('nameA');
1324+
var oldModel = scope.form.nameA;
1325+
scope.nameID = "B";
1326+
scope.$digest();
1327+
expect(scope.form.nameA).toBeUndefined();
1328+
expect(scope.form.nameB).toBe(oldModel);
1329+
expect(scope.form.nameB.$name).toBe('nameB');
1330+
});
1331+
1332+
13201333
describe('"change" event', function() {
13211334
function assertBrowserSupportsChangeEvent(inputEventSupported) {
13221335
// Force browser to report a lack of an 'input' event

0 commit comments

Comments
 (0)