Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 682
Kingsley Simon Avatar asked Mar 17 '23 14:03

Kingsley Simon


2 Answers

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
like image 197
Sam Avatar answered Mar 31 '23 19:03

Sam


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.

like image 42
Austin Mullins Avatar answered Mar 31 '23 18:03

Austin Mullins