Skip to content

Commit

Permalink
fix(select): Clarify documentation and add exception for ngOptions
Browse files Browse the repository at this point in the history
ngOptions introduced `track by` in c32a859.
Using `track by` puts constraints on the value you can use in the interpolation
expression in ngOptions. This patch both documents this and adds an exception
if you use ngOptions in an unsupported way.

Closes angular#6564
  • Loading branch information
janv committed Aug 9, 2014
1 parent 07d5283 commit ac92aea
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/ng/directive/select.js
Expand Up @@ -70,6 +70,13 @@ var ngOptionsMinErr = minErr('ngOptions');
* * `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`).
* <div class="alert alert-warning>
* Do not use `track by` when you have a complex `select` expression that is different from `value`.
* Use `track by` if you want to assign complex objects to the model. Use a complex `select`
* expression like `item.value as item.label for item in items` if your items are object but your
* model values correspond to properties of these objects.
* See an example [in this jsfiddle](http://jsfiddle.net/0vpsv1wa/1/).
* </div>
*
* @example
<example module="selectExample">
Expand Down Expand Up @@ -337,6 +344,12 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) {
// - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
optionGroupsCache = [[{element: selectElement, label:''}]];

if (track && match[2] && valueName !== match[1]) {
throw ngOptionsMinErr('trackSelect',
"Do not use 'track by' when your select ('{0}') is different from your value ('{1}')",
match[1], valueName);
}

if (nullOption) {
// compile the element since there might be bindings in it
$compile(nullOption)(scope);
Expand Down
9 changes: 9 additions & 0 deletions test/ng/directive/selectSpec.js
Expand Up @@ -850,6 +850,15 @@ describe('select', function() {
expect(element.val()).toEqual('4');
});

it('should throw an error when trying to combine track by with a complex select expression', function() {
expect(function() {
createSelect({
'ng-model': 'selected',
'ng-options': 'item.id as item.name for item in values track by item.id'
});
}).toThrowMinErr('ngOptions','trackSelect', "Do not use 'track by' when your select ('item.id') is different from your value ('item')");
});


it('should bind to scope value through experession', function() {
createSelect({
Expand Down

0 comments on commit ac92aea

Please sign in to comment.