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

1
  • 2
    Post the relevant code here at SO Commented Mar 18, 2016 at 9:25

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

3 Comments

@user3334406 I've replaced your select in the Plunker with what Hassan Tariq suggested, it works fine.
Remove ng-repeat from options
OK this works now :) thanks a lot, can someone explain why ng-repeat doesnt work
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.