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

Commit 28662d6

Browse files
committed
feat(input): rename form controls when name is updated
Even though nobody has ever asked for this, we can do it anyway.
1 parent ba0b169 commit 28662d6

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

src/ng/directive/form.js

+12
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,17 @@ 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+
}
140+
};
141+
130142
/**
131143
* @ngdoc method
132144
* @name form.FormController#$removeControl

src/ng/directive/input.js

+7
Original file line numberDiff line numberDiff line change
@@ -2387,8 +2387,15 @@ var ngModelDirective = function() {
23872387
// notify others, especially parent forms
23882388
formCtrl.$addControl(modelCtrl);
23892389

2390+
var unobserveName = attr.$observe('name', function(newValue, oldValue) {
2391+
if (modelCtrl.$name !== newValue) {
2392+
formCtrl.$renameControl(modelCtrl, newValue);
2393+
}
2394+
});
2395+
23902396
scope.$on('$destroy', function() {
23912397
formCtrl.$removeControl(modelCtrl);
2398+
unobserveName();
23922399
});
23932400
},
23942401
post: function(scope, element, attr, ctrls) {

test/ng/directive/inputSpec.js

+13
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)