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

feat(ngOptions): add support for disabling an option #11017

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
75 changes: 52 additions & 23 deletions src/ng/directive/ngOptions.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,15 +94,20 @@ var ngOptionsMinErr = minErr('ngOptions');
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
* * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
* * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
* (for including a filter with `track by`)
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`disable when`** `disable`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
Expand All @@ -116,6 +121,8 @@ var ngOptionsMinErr = minErr('ngOptions');
* element. If not specified, `select` expression will default to `value`.
* * `group`: The result of this expression will be used to group options using the `<optgroup>`
* DOM element.
* * `disable`: The result of this expression will be used to disable the rendered `<option>`
* element. Return `true` to disable.
* * `trackexpr`: Used when working with an array of objects. The result of this expression will be
* used to identify the objects in the array. The `trackexpr` will most likely refer to the
* `value` variable (e.g. `value.propertyName`). With this the selection is preserved
Expand All @@ -129,10 +136,10 @@ var ngOptionsMinErr = minErr('ngOptions');
.controller('ExampleController', ['$scope', function($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'white', shade:'light', notAnOption: true},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
{name:'blue', shade:'dark', notAnOption: true},
{name:'yellow', shade:'light', notAnOption: false}
];
$scope.myColor = $scope.colors[2]; // red
}]);
Expand All @@ -141,6 +148,7 @@ var ngOptionsMinErr = minErr('ngOptions');
<ul>
<li ng-repeat="color in colors">
Name: <input ng-model="color.name">
<input type="checkbox" ng-model="color.notAnOption"> Disabled?
[<a href ng-click="colors.splice($index, 1)">X</a>]
</li>
<li>
Expand All @@ -162,6 +170,12 @@ var ngOptionsMinErr = minErr('ngOptions');
<select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
</select><br/>

Color grouped by shade, with some disabled:
<select ng-model="myColor"
ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
</select><br/>



Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
<hr/>
Expand All @@ -186,16 +200,17 @@ var ngOptionsMinErr = minErr('ngOptions');
*/

// jshint maxlen: false
//000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
// //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@petebacondarwin Here is the syntax change.

// 1: value expression (valueFn)
// 2: label expression (displayFn)
// 3: group by expression (groupByFn)
// 4: array item variable name
// 5: object item key variable name
// 6: object item value variable name
// 7: collection expression
// 8: track by expression
// 4: disable when expression (disableWhenFn)
// 5: array item variable name
// 6: object item key variable name
// 7: object item value variable name
// 8: collection expression
// 9: track by expression
// jshint maxlen: 100


Expand All @@ -215,14 +230,14 @@ var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
// Extract the parts from the ngOptions expression

// The variable name for the value of the item in the collection
var valueName = match[4] || match[6];
var valueName = match[5] || match[7];
// The variable name for the key of the item in the collection
var keyName = match[5];
var keyName = match[6];

// An expression that generates the viewValue for an option if there is a label expression
var selectAs = / as /.test(match[0]) && match[1];
// An expression that is used to track the id of each object in the options collection
var trackBy = match[8];
var trackBy = match[9];
// An expression that generates the viewValue for an option if there is no label expression
var valueFn = $parse(match[2] ? match[1] : valueName);
var selectAsFn = selectAs && $parse(selectAs);
Expand All @@ -237,7 +252,8 @@ var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
function getHashOfValue(viewValue) { return hashKey(viewValue); };
var displayFn = $parse(match[2] || match[1]);
var groupByFn = $parse(match[3] || '');
var valuesFn = $parse(match[7]);
var disableWhenFn = $parse(match[4] || '');
var valuesFn = $parse(match[8]);

var locals = {};
var getLocals = keyName ? function(value, key) {
Expand All @@ -250,11 +266,12 @@ var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
};


function Option(selectValue, viewValue, label, group) {
function Option(selectValue, viewValue, label, group, disabled) {
this.selectValue = selectValue;
this.viewValue = viewValue;
this.label = label;
this.group = group;
this.disabled = disabled;
}

return {
Expand All @@ -275,6 +292,12 @@ var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
var label = displayFn(scope, locals);
watchedArray.push(label);
}

// Only need to watch the disableWhenFn if there is a specific disable expression
if (match[4]) {
var disableWhen = disableWhenFn(scope, locals);
watchedArray.push(disableWhen);
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@petebacondarwin - I rebased your perf and mimicked it with the disableWhenFn

});
return watchedArray;
}),
Expand All @@ -300,7 +323,8 @@ var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
var selectValue = getTrackByValue(viewValue, locals);
var label = displayFn(scope, locals);
var group = groupByFn(scope, locals);
var optionItem = new Option(selectValue, viewValue, label, group);
var disabled = disableWhenFn(scope, locals);
var optionItem = new Option(selectValue, viewValue, label, group, disabled);

optionItems.push(optionItem);
selectValueMap[selectValue] = optionItem;
Expand Down Expand Up @@ -377,7 +401,7 @@ var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
selectCtrl.writeValue = function writeNgOptionsValue(value) {
var option = options.getOptionFromViewValue(value);

if (option) {
if (option && !option.disabled) {
if (selectElement[0].value !== option.selectValue) {
removeUnknownOption();
removeEmptyOption();
Expand All @@ -401,7 +425,7 @@ var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {

var selectedOption = options.selectValueMap[selectElement.val()];

if (selectedOption) {
if (selectedOption && !selectedOption.disabled) {
removeEmptyOption();
removeUnknownOption();
return selectedOption.viewValue;
Expand All @@ -426,18 +450,22 @@ var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
if (value) {
value.forEach(function(item) {
var option = options.getOptionFromViewValue(item);
if (option) option.element.selected = true;
if (option && !option.disabled) option.element.selected = true;
});
}
};


selectCtrl.readValue = function readNgOptionsMultiple() {
var selectedValues = selectElement.val() || [];
return selectedValues.map(function(selectedKey) {
var option = options.selectValueMap[selectedKey];
return option.viewValue;
var selectedValues = selectElement.val() || [],
selections = [];

forEach(selectedValues, function(value) {
var option = options.selectValueMap[value];
if (!option.disabled) selections.push(option.viewValue);
});

return selections;
};
}

Expand Down Expand Up @@ -470,6 +498,7 @@ var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {

function updateOptionElement(option, element) {
option.element = element;
element.disabled = option.disabled;
if (option.value !== element.value) element.value = option.selectValue;
if (option.label !== element.label) {
element.label = option.label;
Expand Down
107 changes: 107 additions & 0 deletions test/ng/directive/ngOptionsSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,57 @@ describe('ngOptions', function() {
expect(options.eq(3)).toEqualOption('c');
});

it('should disable options', function() {

scope.selected = '';
scope.options = [
{ name: 'white', value: '#FFFFFF' },
{ name: 'one', value: 1, unavailable: true },
{ name: 'notTrue', value: false },
{ name: 'thirty', value: 30, unavailable: false }
];
createSelect({
'ng-options': 'o.value as o.name disable when o.unavailable for o in options',
'ng-model': 'selected'
});
var options = element.find('option');

expect(options.length).toEqual(5);
expect(options.eq(1).prop('disabled')).toEqual(false);
expect(options.eq(2).prop('disabled')).toEqual(true);
expect(options.eq(3).prop('disabled')).toEqual(false);
expect(options.eq(4).prop('disabled')).toEqual(false);
});

it('should not write disabled options from model', function() {
scope.selected = 30;
scope.options = [
{ name: 'white', value: '#FFFFFF' },
{ name: 'one', value: 1, unavailable: true },
{ name: 'notTrue', value: false },
{ name: 'thirty', value: 30, unavailable: false }
];
createSelect({
'ng-options': 'o.value as o.name disable when o.unavailable for o in options',
'ng-model': 'selected'
});

var options = element.find('option');

expect(options.eq(3).prop('selected')).toEqual(true);

scope.$apply(function() {
scope.selected = 1;
});

options = element.find('option');

expect(element.val()).toEqualUnknownValue('?');
expect(options.length).toEqual(5);
expect(options.eq(0).prop('selected')).toEqual(true);
expect(options.eq(2).prop('selected')).toEqual(false);
expect(options.eq(4).prop('selected')).toEqual(false);
});

describe('selectAs expression', function() {
beforeEach(function() {
Expand Down Expand Up @@ -1164,6 +1215,31 @@ describe('ngOptions', function() {
expect(element).toEqualSelectValue(scope.selected);
});

it('should bind to object disabled', function() {
scope.selected = 30;
scope.options = [
{ name: 'white', value: '#FFFFFF' },
{ name: 'one', value: 1, unavailable: true },
{ name: 'notTrue', value: false },
{ name: 'thirty', value: 30, unavailable: false }
];
createSelect({
'ng-options': 'o.value as o.name disable when o.unavailable for o in options',
'ng-model': 'selected'
});

var options = element.find('option');

expect(scope.options[1].unavailable).toEqual(true);
expect(options.eq(1).prop('disabled')).toEqual(true);

scope.$apply(function() {
scope.options[1].unavailable = false;
});

expect(scope.options[1].unavailable).toEqual(false);
expect(options.eq(1).prop('disabled')).toEqual(false);
});

it('should insert a blank option if bound to null', function() {
createSingleSelect();
Expand Down Expand Up @@ -1653,6 +1729,37 @@ describe('ngOptions', function() {
expect(element.find('option')[1].selected).toBeTruthy();
});

it('should not write disabled selections from model', function() {
scope.selected = [30];
scope.options = [
{ name: 'white', value: '#FFFFFF' },
{ name: 'one', value: 1, unavailable: true },
{ name: 'notTrue', value: false },
{ name: 'thirty', value: 30, unavailable: false }
];
createSelect({
'ng-options': 'o.value as o.name disable when o.unavailable for o in options',
'ng-model': 'selected',
'multiple': true
});

var options = element.find('option');

expect(options.eq(0).prop('selected')).toEqual(false);
expect(options.eq(1).prop('selected')).toEqual(false);
expect(options.eq(2).prop('selected')).toEqual(false);
expect(options.eq(3).prop('selected')).toEqual(true);

scope.$apply(function() {
scope.selected.push(1);
});

expect(options.eq(0).prop('selected')).toEqual(false);
expect(options.eq(1).prop('selected')).toEqual(false);
expect(options.eq(2).prop('selected')).toEqual(false);
expect(options.eq(3).prop('selected')).toEqual(true);
});


it('should update model on change', function() {
createMultiSelect();
Expand Down