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

Commit

Permalink
feat(ngOptions): add support for disabling an option
Browse files Browse the repository at this point in the history
This patch adds support for disabling options based on model values. The
"disable by" syntax allows for listening to changes on those model values
in order to dynamically enable and disable the options.

The changes prevent disabled options from being written to the model, even
if disabled option selection is attempted programmatically. Support extends
to multiple selections as well.

closes #638
  • Loading branch information
sjbarker committed Feb 8, 2015
1 parent 9d53e5a commit 91061e4
Show file tree
Hide file tree
Showing 2 changed files with 207 additions and 25 deletions.
94 changes: 69 additions & 25 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 by`** `disable` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
* * `label` **`disable by`** `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 by`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`disable by`** `disable`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
Expand All @@ -129,10 +134,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 Down Expand Up @@ -162,6 +167,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 by 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 +197,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]+?))?$/;
// //000011111111110000000000022222222220000000000000000000003333333333000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\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]+?))?$/;
// 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 by expression (disableByFn)
// 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 +227,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 +249,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 disableByFn = $parse(match[4] || '');
var valuesFn = $parse(match[8]);

var locals = {};
var getLocals = keyName ? function(value, key) {
Expand All @@ -250,11 +263,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 @@ -269,8 +283,10 @@ var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
var locals = getLocals(values[key], key);
var label = displayFn(scope, locals);
var selectValue = getTrackByValue(values[key], locals);
var disabledBy = disableByFn(scope, locals);
watchedArray.push(selectValue);
watchedArray.push(label);
watchedArray.push(disabledBy);
});
return watchedArray;
}),
Expand All @@ -296,7 +312,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 = disableByFn(scope, locals);
var optionItem = new Option(selectValue, viewValue, label, group, disabled);

optionItems.push(optionItem);
selectValueMap[selectValue] = optionItem;
Expand All @@ -322,7 +339,7 @@ var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
return {
restrict: 'A',
terminal: true,
require: ['select', '?ngModel'],
require: ['select', 'ngModel'],
link: function(scope, selectElement, attr, ctrls) {

// if ngModel is not defined, we don't need to do anything
Expand Down Expand Up @@ -373,7 +390,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 @@ -398,9 +415,31 @@ var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
var selectedOption = options.selectValueMap[selectElement.val()];

if (selectedOption) {
removeEmptyOption();

if (!selectedOption.disabled) {
removeEmptyOption();
removeUnknownOption();
return selectedOption.viewValue;

// If a disabled option is somehow chosen then we need to render the empty or unknown
// options, especially if they don't exist in options. Otherwise, the select element
// will render the disabled option and the model will be null or empty.
} else if (providedEmptyOption) {
removeUnknownOption();
renderEmptyOption();
} else {
removeEmptyOption();
renderUnknownOption();
}

// jQuery will set selectElement.val() to null if a disabled property is somehow chosen.
// If empty or unknown options have not already been rendered we need to now.
} else if (providedEmptyOption) {
removeUnknownOption();
return selectedOption.viewValue;
renderEmptyOption();
} else {
removeEmptyOption();
renderUnknownOption();
}
return null;
};
Expand All @@ -422,18 +461,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 @@ -466,6 +509,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
138 changes: 138 additions & 0 deletions test/ng/directive/ngOptionsSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,87 @@ 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 by 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 select disabled options', 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 by 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);
});

it('should not update with disabled options', 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 by o.unavailable for o in options',
'ng-model': 'selected'
});

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

// force disabled option to be selected
options.eq(1).prop('selected', true);
options.eq(1).attr('selected', 'selected');

browserTrigger(element, 'change');

options = element.find('option');

expect(options.length).toEqual(5);

expect(scope.selected).toEqual(null);
expect(element.val()).toEqualUnknownValue();
expect(options.eq(0).prop('selected')).toEqual(true);
});

describe('selectAs expression', function() {
beforeEach(function() {
Expand Down Expand Up @@ -1164,6 +1245,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 by 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 +1759,38 @@ describe('ngOptions', function() {
expect(element.find('option')[1].selected).toBeTruthy();
});

//TODO: test multiple
it('should not read disabled selections', 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 by 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

0 comments on commit 91061e4

Please sign in to comment.