loxdog
loxdog

Reputation: 1007

Different value of selected option in AngularJS select ng-repeat

I have a drop-down list that I'm trying to create where the value displayed in the drop-down is different to the options available - I'm using angularjs for this purpose. For example, if I had the following text, I'd want to display the full value when the user opens the drop-down:

A - A is for Apple

B - B is for Banana

But on the page I only want to display A or B, not the full description, as in this picture: enter image description here

This is the closest I've got so far (where my list of objects are just objects with a Value and Description property) but I can't seem to show the short value in the dropdown, although I know I've seen this kind of set up online on various sites.

<select>
 <option ng-repeat="item in myObject.Options" value="{{item.Value}}" title="{{item.Description}}">{{item.Description}}</option>
</select>

Where the object would look something like

var myObject = { "Options" : [
{ "Value":"A" , "Description":"A is for Apple" },
{ "Value":"B" , "Description":"B is for Banana" },
{ "Value":"C" , "Description":"C is for Cherry" } ]};

Upvotes: 2

Views: 2044

Answers (2)

Santosh Shinde
Santosh Shinde

Reputation: 6053

This is not possible, because you have uses the HTML select component that is not able to distinguish between the displayed text in the dropdown and the shown value.

However you could build an own directive for implementing a similar behaviour, for example with a bootstrap dropdown menu or md-select.

For example :

 <md-select md-selected-text="selectedItem.Value" ng-model="selectedItem">
      <md-option ng-repeat="item in items" ng-value="item">
         {{ item.Description }}
     </md-option>
 </md-select>

Hope this will help you !

Upvotes: 2

Prerak Sola
Prerak Sola

Reputation: 10019

If you only want to display the Value part, you can use this:

<select>
    <option ng-repeat="item in myObject.Options" value="{{item.Value}}" title="{{item.Description}}">
        {{item.Value}} - {{item.Description}}
    </option>
</select>

Example:

var app = angular.module('app', []);

app.controller('TestController', function($scope) {

  $scope.myObject = {
    "Options": [{
      "Value": "A",
      "Description": "A is for Apple"
    }, {
      "Value": "B",
      "Description": "B is for Banana"
    }, {
      "Value": "C",
      "Description": "C is for Cherry"
    }]
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller='TestController'>
  <select>
    <option ng-repeat="item in myObject.Options" value="{{item.Value}}" title="{{item.Description}}">{{item.Value}} - {{item.Description}} </option>
  </select>
</div>

Upvotes: 0

Related Questions