Skip to content

Commit 87b63ac

Browse files
author
Yaroslav Ulanovych
committed
fix(ngModel): handle interpolated names for ngModel
Fix that controls with interpolated names don't publish themselves to the form, cause the name isn't known at publishing time. Refers angular#1404
1 parent 12b6deb commit 87b63ac

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

src/ng/directive/input.js

+15-1
Original file line numberDiff line numberDiff line change
@@ -1110,7 +1110,21 @@ var ngModelDirective = function() {
11101110
var modelCtrl = ctrls[0],
11111111
formCtrl = ctrls[1] || nullFormCtrl;
11121112

1113-
formCtrl.$addControl(modelCtrl);
1113+
// Support of the interpolation in the name attribute,
1114+
// when the name changes, the control is republished in the form.
1115+
// We rely on the behaviour of the attribute interpolation directive,
1116+
// which sets the value to undefined during compilation.
1117+
if (attr.name) {
1118+
formCtrl.$addControl(modelCtrl);
1119+
} else {
1120+
attr.$observe('name', function(name) {
1121+
if (modelCtrl.$name) {
1122+
formCtrl.$removeControl(modelCtrl);
1123+
}
1124+
modelCtrl.$name = name;
1125+
formCtrl.$addControl(modelCtrl);
1126+
});
1127+
}
11141128

11151129
element.bind('$destroy', function() {
11161130
formCtrl.$removeControl(modelCtrl);

test/ng/directive/formSpec.js

+16-2
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,7 @@ describe('form', function() {
111111
expect(scope.formB.$error.required).toBe(false);
112112
});
113113

114-
115-
it('should publish widgets', function() {
114+
it('should publish widgets with static names', function() {
116115
doc = jqLite('<form name="form"><input type="text" name="w1" ng-model="some" /></form>');
117116
$compile(doc)(scope);
118117

@@ -124,6 +123,21 @@ describe('form', function() {
124123
expect(widget.$invalid).toBe(false);
125124
});
126125

126+
it('should publish widgets with dynamic names', function() {
127+
doc = jqLite('<form name="form"><input type="text" name="{{name}}" ng-model="some" /></form>');
128+
$compile(doc)(scope);
129+
130+
scope.name = 'w1';
131+
scope.$digest();
132+
var widget = scope.form.w1;
133+
expect(widget).toBeDefined();
134+
135+
scope.name = 'w2';
136+
scope.$digest();
137+
expect(scope.form.w1).toBeUndefined();
138+
expect(scope.form.w2).toBeDefined();
139+
expect(scope.form.w2).toBe(widget);
140+
});
127141

128142
describe('preventing default submission', function() {
129143

0 commit comments

Comments
 (0)