Artemis Artemis - 1 month ago 8
AngularJS Question

print everything from an option with md-select angular js

Hi everyone I am trying to learn angularjs.

I have made this select:

<label class="md-title" for="yachtId">Choose:</label>
<select name="yachtId" id="yachtId" ng-options="selectedYacht.title for
selectedYacht in yachtIds.availableOptions track by selectedYacht.id"
ng-model="yachtIds.selectedOption" >
</select>


I get my data in json format and it's like this:

$scope.yachtIds = {
availableOptions":[
{"id":"2","title":"Name 1","maxCapacity":"5"},
{"id":"7","title":"Name 2","maxCapacity":"8"}
]}


and with this line I get what the user selected:

selectedYacht = {{yachtIds.selectedOption}}


the output is this: selectedYacht = {"id":"7","title":"Name 2","maxCapacity":"8"}

The problem is, I am trying to make the same select with md-select but I can't figure out how to print everything from the user's selection. With the below code, I get only the name.

<md-input-container flex="100">
<label class="md-title" for="yachtId">Desired yacht:</label>
<md-select ng-model="yachtIds.selectedOption" name="yachtId" id="yachtId">
<md-option ng-value="t.title" data-ng-repeat="t in yachtIds.availableOptions">
{{ t.title }}
</md-option>
</md-select>
</md-input-container>


So, the output is this: selectedYacht = Name 2, but I want it to be like the previous one (selectedYacht = {"id":"7","title":"Name 2","maxCapacity":"8"}).

Any help? Thanks in advance.

Answer

Change your ng-value attribute to t instead of t.title, and add the trackBy model option:

<md-select ng-model="yachtIds.selectedOption" ng-model-options="{trackBy: '$value.id'}" name="yachtId" id="yachtId">
    <md-option ng-value="t" data-ng-repeat="t in yachtIds.availableOptions">
        {{ t.title }}
    </md-option>
</md-select>
Comments