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

fix(select): ensure that at least one option has the selected attribute set #8429

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/ng/directive/select.js
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,7 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) {
(element = optionTemplate.clone())
.val(option.id)
.prop('selected', option.selected)
.attr('selected', option.selected)
.text(option.label);
}

Expand Down
41 changes: 41 additions & 0 deletions test/ng/directive/selectSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1008,6 +1008,47 @@ describe('select', function() {

expect(scope.selected).toBe(scope.values[1]);
});


it('should ensure that at least one option element has the "selected" attribute', function() {
createSelect({
'ng-model': 'selected',
'ng-options': 'item.id as item.name for item in values'
});

scope.$apply(function() {
scope.values = [{id: 10, name: 'A'}, {id: 20, name: 'B'}];
});
expect(element.val()).toEqual('?');
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');

scope.$apply(function() {
scope.selected = 10;
});
// Here the ? option should disappear and the first real option should have selected attribute
expect(element.val()).toEqual('0');
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');

// Here the selected value is changed but we don't change the selected attribute
scope.$apply(function() {
scope.selected = 20;
});
expect(element.val()).toEqual('1');
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');

scope.$apply(function() {
scope.values.push({id: 30, name: 'C'});
});
expect(element.val()).toEqual('1');
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');

// Here the ? option should reappear and have selected attribute
scope.$apply(function() {
scope.selected = undefined;
});
expect(element.val()).toEqual('?');
expect(element.find('option').eq(0).attr('selected')).toEqual('selected');
});
});


Expand Down