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

Commit 79538af

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 Conflicts: test/ng/directive/selectSpec.js
1 parent bcfa64e commit 79538af

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
@@ -566,6 +566,7 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) {
566566
(element = optionTemplate.clone())
567567
.val(option.id)
568568
.prop('selected', option.selected)
569+
.attr('selected', option.selected)
569570
.text(option.label);
570571
}
571572

test/ng/directive/selectSpec.js

+41
Original file line numberDiff line numberDiff line change
@@ -994,6 +994,47 @@ describe('select', function() {
994994
expect(element.find('option').eq(0).prop('selected')).toBeTruthy();
995995
expect(element.find('option').length).toEqual(2);
996996
});
997+
998+
999+
it('should ensure that at least one option element has the "selected" attribute', function() {
1000+
createSelect({
1001+
'ng-model': 'selected',
1002+
'ng-options': 'item.id as item.name for item in values'
1003+
});
1004+
1005+
scope.$apply(function() {
1006+
scope.values = [{id: 10, name: 'A'}, {id: 20, name: 'B'}];
1007+
});
1008+
expect(element.val()).toEqual('?');
1009+
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');
1010+
1011+
scope.$apply(function() {
1012+
scope.selected = 10;
1013+
});
1014+
// Here the ? option should disappear and the first real option should have selected attribute
1015+
expect(element.val()).toEqual('0');
1016+
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');
1017+
1018+
// Here the selected value is changed but we don't change the selected attribute
1019+
scope.$apply(function() {
1020+
scope.selected = 20;
1021+
});
1022+
expect(element.val()).toEqual('1');
1023+
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');
1024+
1025+
scope.$apply(function() {
1026+
scope.values.push({id: 30, name: 'C'});
1027+
});
1028+
expect(element.val()).toEqual('1');
1029+
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');
1030+
1031+
// Here the ? option should reappear and have selected attribute
1032+
scope.$apply(function() {
1033+
scope.selected = undefined;
1034+
});
1035+
expect(element.val()).toEqual('?');
1036+
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');
1037+
});
9971038
});
9981039

9991040

0 commit comments

Comments
 (0)