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

ngOptions: always set selected attribute for selected options #14125

Closed
wants to merge 1 commit into from
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
8 changes: 7 additions & 1 deletion src/ng/directive/ngOptions.js
Original file line number Diff line number Diff line change
Expand Up @@ -468,14 +468,20 @@ var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
var option = options.getOptionFromViewValue(value);

if (option && !option.disabled) {
// Don't update the option when it is already selected.
// For example, the browser will select the first option by default. In that case,
// most properties are set automatically - except the `selected` attribute, which we
// set always

if (selectElement[0].value !== option.selectValue) {
removeUnknownOption();
removeEmptyOption();

selectElement[0].value = option.selectValue;
option.element.selected = true;
option.element.setAttribute('selected', 'selected');
}

option.element.setAttribute('selected', 'selected');
} else {
if (value === null || providedEmptyOption) {
removeUnknownOption();
Expand Down
34 changes: 34 additions & 0 deletions test/ng/directive/ngOptionsSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,40 @@ describe('ngOptions', function() {

});

it('should set the "selected" attribute and property on selected options', function() {
scope.values = [{
id: 'FF0000',
display: 'red'
}, {
id: '0000FF',
display: 'blue'
}];
scope.selected = 'FF0000';

createSelect({
'ng-model': 'selected',
'ng-options': 'option.id as option.display for option in values'
});
scope.$digest();

var options = element.find('option');
expect(options.length).toEqual(2);
expect(options.eq(0)).toEqualOption('FF0000', 'red');
expect(options.eq(1)).toEqualOption('0000FF', 'blue');

expect(options.eq(0)[0].getAttribute('selected')).toBe('selected');
expect(options.eq(0).attr('selected')).toBe('selected');
expect(options.eq(0)[0].selected).toBe(true);
expect(options.eq(0).prop('selected')).toBe(true);

scope.selected = '0000FF';
scope.$digest();

expect(options.eq(1)[0].getAttribute('selected')).toBe('selected');
expect(options.eq(1).attr('selected')).toBe('selected');
expect(options.eq(1)[0].selected).toBe(true);
expect(options.eq(1).prop('selected')).toBe(true);
});

it('should render zero as a valid display value', function() {
createSingleSelect();
Expand Down