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

Commit 3247b99

Browse files
committed
fix(select): add / remove 'selected' attribute for select[multiple]
1 parent 4e9208f commit 3247b99

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

src/ng/directive/select.js

+15-1
Original file line numberDiff line numberDiff line change
@@ -606,9 +606,23 @@ var selectDirective = function() {
606606
// Write value now needs to set the selected property of each matching option
607607
selectCtrl.writeValue = function writeMultipleValue(value) {
608608
var items = new HashMap(value);
609+
var optionSelected = false;
610+
609611
forEach(element.find('option'), function(option) {
610-
option.selected = isDefined(items.get(option.value)) || isDefined(items.get(selectCtrl.selectValueMap[option.value]));
612+
var optionIsDefined = isDefined(items.get(option.value)) || isDefined(items.get(selectCtrl.selectValueMap[option.value]));
613+
option.selected = optionIsDefined;
614+
615+
if (optionIsDefined) {
616+
option.setAttribute('selected', 'selected');
617+
optionSelected = true;
618+
} else {
619+
option.removeAttribute('selected');
620+
}
611621
});
622+
623+
if (!optionSelected) {
624+
selectCtrl.selectEmptyOption();
625+
}
612626
};
613627

614628
// we have to do it on each watch since ngModel watches reference, but

test/ng/directive/selectSpec.js

+28
Original file line numberDiff line numberDiff line change
@@ -1144,6 +1144,34 @@ describe('select', function() {
11441144
});
11451145

11461146

1147+
it('should add / remove the "selected" attribute on selected / unselected options', function() {
1148+
compile(
1149+
'<select name="select" ng-model="selected" multiple>' +
1150+
'<option value=""></option>' +
1151+
'<option>A</option>' +
1152+
'<option>B</option>' +
1153+
'<option>C</option>' +
1154+
'</select>');
1155+
1156+
scope.selected = ['C'];
1157+
scope.$apply();
1158+
1159+
expect(element.find('option')[0].value).toBe('');
1160+
1161+
expect(element.find('option')[0]).not.toBeMarkedAsSelected();
1162+
expect(element.find('option')[3]).toBeMarkedAsSelected();
1163+
1164+
scope.$apply('selected = []');
1165+
expect(element.find('option')[0]).toBeMarkedAsSelected();
1166+
1167+
scope.selected = ['B', 'C'];
1168+
scope.$apply();
1169+
expect(element.find('option')[0]).not.toBeMarkedAsSelected();
1170+
expect(element.find('option')[2]).toBeMarkedAsSelected();
1171+
expect(element.find('option')[3]).toBeMarkedAsSelected();
1172+
});
1173+
1174+
11471175
describe('calls to $render', function() {
11481176

11491177
var ngModelCtrl;

0 commit comments

Comments
 (0)