1

I have an object with AllCountries and SelectedCoutry. I want to list all countries on a <select> and select the option with ng-model by the value of SelectedCountry.

But the default value of combobox gets selected null.

Example:

angular.module('ngPatternExample', [])
    .controller('ExampleController', ['$scope', function($scope) {
      $scope.OBJ = {
                    "OBJ": {
                      "AllCountries": [
                        {
                          "country": "USA",
                          "id": 1
                        },
                        {
                          "country": "Mexico",
                          "id": 2
                        },
                        {
                          "country": "Canada",
                          "id": 3
                        }
                      ],
                      "SelectedCountry": {
                        "country_id": 1,
                      }
                    }
                }
                
      $scope.AM = $scope.OBJ.OBJ;
    }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ngPatternExample">
<div ng-controller="ExampleController">
  selected country: {{AM.SelectedCountry.country_id}} <br/>
  <select class="form-control" ng-model="AM.SelectedCountry.country_id">
    <option value=""> --- </option>
    <option ng-repeat="co in AM.AllCountries" value="{{co.id}}"> {{co.country}} </option>
  </select>
</div>
  </body>

(http://plnkr.co/edit/PI3tOrIMSTMwGC0rYA5q?p=preview)

p.s A good explanation why this doesnt work allways in Angular would be great

user2314737
  • 27,088
  • 20
  • 102
  • 114
user3334406
  • 337
  • 4
  • 16

2 Answers2

3

Replace your select with this

<select class="form-control"  ng-options="co.id as co.country for co in OBJ.OBJ.AllCountries" ng-model="AM.SelectedCountry.country_id">
    <option value=""> --- </option>
</select>
Erazihel
  • 7,295
  • 6
  • 30
  • 53
Hassan Tariq
  • 730
  • 7
  • 15
2

Use ngOptions directive instead of repeating options in the select box by yourself.

<select 
  class="form-control"
  ng-model="AM.SelectedCountry.country_id"
  ng-options="co.id as co.country for co in AM.AllCountries">
    <option value=""> --- </option>
</select>

Updated plunk: http://plnkr.co/edit/FZcJVkJQlbLM3k544s8S?p=preview

kvetis
  • 6,682
  • 1
  • 28
  • 48