简体   繁体   中英

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 .

That is what ng-model is for. I suggest you initialize myCountry in a controller. Note that myCountry should ideally have the same format as countries (eg: {"code": "ZA", "name": "South Africa"} ).

Edit: I am adding an example from my own project:

<select class="small" data-ng-change="goToTask(current_task.id)" data-ng-model="current_task" data-ng-options="task.name for task in tasks track by task.id"></select>

In Controller:

$scope.current_task = { id: $scope.myService.getCurrentTaskId() };

What is important here is that current_task is at minimum a hash containing the id key.

Edit2: I was thinking about the sorting problem with the track by. I think you can use select instead, eg: `ng-options="select country.code as country.name for country in countries". I haven't tried it but from the angular docs, it should work.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM