MarcosF8
MarcosF8

Reputation: 2008

Select by name and get the Id of the selected item with Angular

I am working in an MVC project with HTML and angular. I have a select list which get selected based on a name entered in an input box, but I am not able to get the id.

This works but I don't get the Id of the selected item:

<input type="text" ng-model="selectedCountry">
    <select class="form-control" 
    ng-model="selectedCountry" 
    ng-options="country.name as country.name for country in countries">
<option value="">Select Country</option>

And this is not working, as I am not able to select by the name and get the id:

<input type="text" ng-model="selectedCountry">
  <select class="form-control" 
    ng-model="selectedCountry" 
    ng-options="country.id as country.name for country in countries">
<option value="">Select Country</option>

Here is the plunker: Plunker

Thanks for the help!

Upvotes: 1

Views: 15279

Answers (5)

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16811

I don't think that's possible when you use the same model on different select which are using different keys for the model.

I would go with using the name in both models and then fetching the id from the array:

$scope.getId = function(){
    var co = $scope.countries.filter(function (el) {  return el.name == $scope.selectedCountry });
      if(typeof co !== 'undefined' && co.length > 0){
        $scope.selectedId =co[0].id;
      }else{
        $scope.selectedId = null;
      }
  };

plunker here

Upvotes: 0

hrdkisback
hrdkisback

Reputation: 908

<select class="form-control"  data-ng-change="call(country.id)"
        ng-model="country.id" 
        ng-options="country.id as country.name for country in countries">
    <option value="">Select Country</option>
  </select>

Upvotes: 2

Dioux
Dioux

Reputation: 106

Or

<input type="text" ng-model="selectedCountry.name">
  <select class="form-control" 
        ng-model="selectedCountry" 
        ng-options="country as country.name for country in countries">
    <option value="">Select Country</option>

  </select>

In your HTML

and

$scope.selectedCountry = {};

in your javascript

Upvotes: 0

AimeTPGM
AimeTPGM

Reputation: 241

try this

html

<input type="text" ng-model="selectedCountryId">
  <select class="form-control" ng-model="selectedCountryId">
  <option ng-repeat="country in countries" value="{{country.id}}">{{country.name}}</option>
</select>
<div>selected country id: {{selectedCountryId}} </div>

in controller add $scope.selectedCountryId = "";

enter image description here

hope it helps

Upvotes: 0

jbrown
jbrown

Reputation: 3025

In order for the second scenario to work you'll need to get the id of the country in your controller like this:

  $scope.selectedCountry = $scope.countries.find(function(country) {
    return country.name === "Italy";
  }).id;

Upvotes: 1

Related Questions