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

fix(ngValue): setting binding to undefined should update the DOM value to an empty string #15605

Closed
wants to merge 8 commits into from
5 changes: 4 additions & 1 deletion src/ng/directive/input.js
Original file line number Diff line number Diff line change
Expand Up @@ -2142,7 +2142,10 @@ var ngValueDirective = function() {
* makes it possible to use ngValue as a sort of one-way bind.
*/
function updateElementValue(element, attr, value) {
element.prop('value', value);
// Support: IE9 only
// In IE9 values are converted to string (e.g. `input.value = null` results in `input.value === 'null'`).
var propValue = isDefined(value) ? value : (msie === 9) ? '' : null;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is a good idea to add a comment here explaining the IE9 issue. Something like:

// Support: IE9 only
// In IE9 values are converted to string (e.g. `input.value = null` results in `input.value === 'null'`).

element.prop('value', propValue);
attr.$set('value', value);
}

Expand Down
20 changes: 20 additions & 0 deletions test/ng/directive/inputSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4211,6 +4211,26 @@ describe('input', function() {
expect(inputElm[0].getAttribute('value')).toBe('something');
});

it('should clear the "dom" value property and attribute when the value is undefined', function() {
var inputElm = helper.compileInput('<input type="text" ng-value="value">');

$rootScope.$apply('value = "something"');

expect(inputElm[0].value).toBe('something');
expect(inputElm[0].getAttribute('value')).toBe('something');

$rootScope.$apply(function() {
delete $rootScope.value;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: This could be $rootScope.$apply('value = undefined'). (just sayin'...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not going to fix this nit as I prefer delete. If you prefer me to use undefined anyway, I'll update it!

});

expect(inputElm[0].value).toBe('');
// Support: IE 9-11
// In IE it is not possible to remove the `value` attribute from an input element.
if (!msie) {
expect(inputElm[0].getAttribute('value')).toBeNull();
}
});

they('should update the $prop "value" property and attribute after the bound expression changes', {
input: '<input type="text" ng-value="value">',
textarea: '<textarea ng-value="value"></textarea>'
Expand Down