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

Commit 25a476e

Browse files
fix(select): ensure that at least one option has the selected attribute set
Using `prop` to set selected is correct programmatically but accessibility guidelines suggest that at least on item should have the `selected` attribute set. Closes #8366 Closes #8429
1 parent dd2a803 commit 25a476e

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/ng/directive/select.js

+1
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,7 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) {
576576
(element = optionTemplate.clone())
577577
.val(option.id)
578578
.prop('selected', option.selected)
579+
.attr('selected', option.selected)
579580
.text(option.label);
580581
}
581582

test/ng/directive/selectSpec.js

+41
Original file line numberDiff line numberDiff line change
@@ -1008,6 +1008,47 @@ describe('select', function() {
10081008

10091009
expect(scope.selected).toBe(scope.values[1]);
10101010
});
1011+
1012+
1013+
it('should ensure that at least one option element has the "selected" attribute', function() {
1014+
createSelect({
1015+
'ng-model': 'selected',
1016+
'ng-options': 'item.id as item.name for item in values'
1017+
});
1018+
1019+
scope.$apply(function() {
1020+
scope.values = [{id: 10, name: 'A'}, {id: 20, name: 'B'}];
1021+
});
1022+
expect(element.val()).toEqual('?');
1023+
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');
1024+
1025+
scope.$apply(function() {
1026+
scope.selected = 10;
1027+
});
1028+
// Here the ? option should disappear and the first real option should have selected attribute
1029+
expect(element.val()).toEqual('0');
1030+
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');
1031+
1032+
// Here the selected value is changed but we don't change the selected attribute
1033+
scope.$apply(function() {
1034+
scope.selected = 20;
1035+
});
1036+
expect(element.val()).toEqual('1');
1037+
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');
1038+
1039+
scope.$apply(function() {
1040+
scope.values.push({id: 30, name: 'C'});
1041+
});
1042+
expect(element.val()).toEqual('1');
1043+
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');
1044+
1045+
// Here the ? option should reappear and have selected attribute
1046+
scope.$apply(function() {
1047+
scope.selected = undefined;
1048+
});
1049+
expect(element.val()).toEqual('?');
1050+
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');
1051+
});
10111052
});
10121053

10131054

0 commit comments

Comments
 (0)