Kingsley Simon
Kingsley Simon

Reputation: 2210

Get Selected Text of Angular ng-option dropdown list

I have this drop-down list in my angular code:

<div class="btn-group" dropdown>
            <select class="selected_location" ng-options="perlocation.id as perlocation.name for perlocation in locations" ng-model="cleaningServiceLocation">
            <option value="">Please Select Location</option>
            </select> 
    <div>

Now in my controller I can easily call the selected value as:

$scope.cleaningServiceLocation 

How can I get the text, or in my case, the name of the selected location?

Upvotes: 4

Views: 4566

Answers (2)

Sam
Sam

Reputation: 4484

You can make model (perlocation) as object instead of (perlocation.id)-

<select class="selected_location" ng-options="perlocation as perlocation.name for perlocation in locations" ng-model="cleaningServiceLocation">

And access it as -

$scope.cleaningServiceLocation.name

Upvotes: 5

Austin Mullins
Austin Mullins

Reputation: 7427

The easy way would be to loop through the locations array every time the value changes and grab the name property from the location whose id matches $scope.cleaningServiceLocation:

$scope.getName = function(id) {
  for (var i = 0; i < $scope.locations.length; i++) {
    if ($scope.locations[i].id == id) {
      return $scope.locations[i].name;
    }
  }

  return "";
}

Try it in a Plunker.

Upvotes: 2

Related Questions