Skip to content

Commit cc5e8e5

Browse files
committed
Clarify documentation and add exception for ngOptions
angular#6564
1 parent 07d5283 commit cc5e8e5

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/ng/directive/select.js

+13
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,13 @@ var ngOptionsMinErr = minErr('ngOptions');
7070
* * `trackexpr`: Used when working with an array of objects. The result of this expression will be
7171
* used to identify the objects in the array. The `trackexpr` will most likely refer to the
7272
* `value` variable (e.g. `value.propertyName`).
73+
* <div class="alert alert-warning>
74+
* Do not use `track by` when you have a complex `select` expression that is different from `value`.
75+
* Use `track by` if you want to assign complex objects to the model. Use a complex `select`
76+
* expression like `item.value as item.label for item in items` if your items are object but your
77+
* model values correspond to properties of these objects.
78+
* See an example [in this jsfiddle](http://jsfiddle.net/0vpsv1wa/1/).
79+
* </div>
7380
*
7481
* @example
7582
<example module="selectExample">
@@ -337,6 +344,12 @@ var selectDirective = ['$compile', '$parse', function($compile, $parse) {
337344
// - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
338345
optionGroupsCache = [[{element: selectElement, label:''}]];
339346

347+
if (track && match[2] && valueName !== match[1]) {
348+
throw ngOptionsMinErr('trackSelect',
349+
"Do not use 'track by' when your select ('{0}') is different from your value ('{1}')",
350+
match[1], valueName);
351+
}
352+
340353
if (nullOption) {
341354
// compile the element since there might be bindings in it
342355
$compile(nullOption)(scope);

test/ng/directive/selectSpec.js

+9
Original file line numberDiff line numberDiff line change
@@ -850,6 +850,15 @@ describe('select', function() {
850850
expect(element.val()).toEqual('4');
851851
});
852852

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

854863
it('should bind to scope value through experession', function() {
855864
createSelect({

0 commit comments

Comments
 (0)