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 selectCtrl
from the model. If a disabled selection is present on the model, normal
unknown or empty functionality kicks in.

closes #638
  • Loading branch information
sjbarker committed Feb 11, 2015
1 parent c211e7a commit 6e468c8
Show file tree
Hide file tree
Showing 2 changed files with 156 additions and 24 deletions.
73 changes: 49 additions & 24 deletions src/ng/directive/ngOptions.js
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 @@ -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 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 +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]+?))?$/;
// //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 +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 disableByFn = $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 @@ -269,8 +286,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 +315,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 +342,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 +393,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 @@ -397,7 +417,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 @@ -422,18 +442,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 +490,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
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 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 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 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);
});

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 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 +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 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 6e468c8

Please sign in to comment.