Search code examples
javascriptangularjsng-options

Select default value with condition in ng-options


I have an angular app with the following array:

countries = [{"code": "ZA", "name": "South Africa"}, {"code": "CH", "name": "Switzerland"}]

with a Jade select as follow:

select(ng-model='myCountry', ng-options='country.name for country in countries')

What I would like to do is to pre-select a country based on the code for example:

select(ng-model='myCountry', ng-options='country.name for country in countries', ng-selected='country.code=="CH"')

Obviously, this solution doesn't work as ng-selected is not intended to be used in a select but in an option tag.

It is important for me to use a conditional selection and not a default index value like in the angularJS example.


Solution

  • From your sample above it looks like you should do this in your controller:

    $scope.myCountry = $scope.countries.filter(function(c){ return  c.code==="CH"})[0];
    

    Like this:

    <script>
      function MyCntrl($scope) {
        $scope.countries = [{"code": "ZA", "name": "South Africa"}, {"code": "CH", "name": "Switzerland"}];
        $scope.myCountry = $scope.countries.filter(function(c){ return  c.code==="CH"})[0];
      }
      </script>
    

    Or you could try building the select with and ngRepeat which seems to be closer to what you need, like this:

    Online Demo

    <body ng-app="">
        <script>
      function MyCntrl($scope) {
        $scope.countries = [{"code": "ZA", "name": "South Africa"}, {"code": "CH", "name": "Switzerland"}];      
      }
      </script>
      <div ng-controller="MyCntrl">    
        <select ng-model="myCountry" >
          <option ng-selected="c.code=='CH'" ng-repeat="c in countries">{{c.name}}</option>
        </select><br>
      {{myCountry |json}}
    </body>