I would like to know if I can include additional logic in angular ng-options attribute for a Select element.
In one case, I have a set of options that are flat and have no groupings associated with them. In another, I have multiple options that may have the same description, however their Id's vary because they are each grouped into categories. Based on the data sent over, I would like to display them as either grouped or not grouped.
GROUPED:
<select ng-model="tcCtrl.SelectedItem"
ng-options="item.Id + ' - ' + item.Description
group by item.GroupDescription
for item in ctrl.Context.ItemList }"></select>
NOT GROUPED:
<select ng-model="tcCtrl.SelectedItem"
ng-options="item.Id + ' - ' + item.Description
for item in ctrl.Context.ItemList }"></select>
CONDITIONALLY GROUPED ??
If at all possible, I would like to avoid have two separate instances of the select element, however I do no think that the parser for the ngSelectDirective really takes any conditional logic.
Thoughts at good ways to implement something like this?
UPDATE: Here's how the suggested attempt looks...even without any of the 'logic' to build the string.
var optionStr = "item.Id for item in ctrl.Context.Items";
...<select ng-options="{{ ctrl.optionStr }}"></select>...
Problem is when I try binding it the binding doesn't seem to want to stick. If I take the same generated string and replace the {{ property }} then it works fine. I can even confirm in chrome that the string is being rendered in the mark-up.
UPDATE: I have proven that the suggested method does work in a very sterile environment. http://jsfiddle.net/xbws8r5h/
There must be something in my environment that is a variant.
Just generate your ng-options expression in JavaScript (controller). Depending of some conditional logic assign different expression.
For example:
<select ng-model="tcCtrl.SelectedItem"
ng-options="{{ selectOptions }}"></select>
And your controller might look like:
if(groupCondition){
$scope.selectOptions = "item.Id + ' - ' + item.Description
group by item.GroupDescription
for workType in ctrl.Context.ItemList";
} else {
$scope.selectOptions = "item.Id + ' - ' + item.Description for workType in ctrl.Context.ItemList";
}
Also, shouldn't expression be "... for item in ctrl.Context.ItemList" instead of workType in your case?
See also this answer .
来源:https://stackoverflow.com/questions/26125226/how-might-i-implement-conditional-grouping-in-a-select-element-using-angular