bmnepali
bmnepali

Reputation: 456

How to display the selected value in select option field from the json object fetched form server angularjs

I have fetched a json object with the list of countries. And now i want to display the selected name of the country in the select option box. I've tried different ways but there always keep showing the blank value.

Note:countries is the json object having the list of countries with key value pair. It used to display the select option in the view. And tabs[0].data.country is the value of country id which is to be selected.

Some of the codes i have tried: Code to display the selected country name: enter image description here

Code to display the select option in View: enter image description here

Output: enter image description here

Upvotes: 0

Views: 1352

Answers (2)

bmnepali
bmnepali

Reputation: 456

Well finally, here is the snippet that solved my problem.

html

<div ng-controller="ExampleController">
   <form name="myForm">
     <label for="mySelect">Make a choice:</label>
     <select name="mySelect" id="mySelect"
        ng-options="option.name for option in data.availableOptions track by option.id" ng-model="data.selectedOption">
     </select>
   </form>
</div>

js

angular.module('defaultValueSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ],
     selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
     };
 }]);

For more information you can go to this link

Also another useful tutorial here

Upvotes: 0

km1882
km1882

Reputation: 750

Convert you json object into an array of objects first, and then you do something like

    <select name="countries" id="contries" ng-model="vm.country">
      <option ng-repeat="country in vm.countries" value="{{country.id}}">{{country.name}}</option>
    </select>

Just loop over them and pick what you want from the list. Full documentation here: https://docs.angularjs.org/api/ng/directive/select

Upvotes: 0

Related Questions