Naigel
Naigel

Reputation: 9644

Angular ng-options to ng-repeat with extra options

I have a <select> element and I use ng-options to add insert available values, my code is like

<select ng-model="selectedCollection"
    ng-options="collection.collectionName for collection in seriesCollection">
</select>

This works fine, and in $scope.selectedCollection I have the whole collection object.

Now I need to add some extra <option> elements based on some parameters. I think the best way is avoid using ng-options and do something like this

<select ng-model="selectedCollection"
    <option value='c1' ng-if="case1">somevalue</option>
    <option value='c2' ng-if="case2">somevalue2</option>
    <option ng-repeat="collection in seriesCollection">
        {{ collection.collectionName }}
    </option>
    <option value='c3' ng-if="case3">somevalue3</option>
</select>

This way selectedCollection contains a string named c1, c2 or c3 when a "static" option is selected, but I would like it to contain the whole collection object when one of them is selected.

I tried with <option ng-repeat="collection in seriesCollection" value="{{ collection }}"> but then the stored value is not the collection object but a string representing it's serialization. How can I do?

Upvotes: 0

Views: 661

Answers (1)

maurycy
maurycy

Reputation: 8465

Unfortunately what you try to achieve can't be done. It is the ngOptions directive that takes care of binding the object to model and any other method like ngRepeat will set model as string therefore value can't be object and mixing ngOptions with html option will not work.

You can utilise ngChange or add the cases to the collections and use filter to return only the one that should be displayed

Upvotes: 1

Related Questions