javascript - 在 ng-options 中选择带有条件的默认值

标签 javascript angularjs ng-options

我有一个带有以下数组的 Angular 应用程序:

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

使用 Jade 选择如下:

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

我想做的是根据代码预先选择一个国家/地区,例如:

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

显然,这个解决方案不起作用,因为 ng-selected 不适合在 select 中使用,而是在选项标签中使用。

对我来说,使用条件选择而不是像 angularJS example 中那样的默认索引值很重要。 。

最佳答案

从上面的示例来看,您应该在 Controller 中执行此操作:

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

像这样:

<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>

或者您可以尝试使用 和 ngRepeat 构建选择,这似乎更接近您需要的内容,如下所示:

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>

关于javascript - 在 ng-options 中选择带有条件的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23876935/

相关文章:

angularjs - 如何使用 $broadcast 发送对象?

javascript - 如何根据我当前所在的页面/路线使用 angular ng-hide?

javascript - jQuery datepicker 用一位数字解析年份

javascript - Gulp uglify 无法处理箭头函数

html - 如何在 ng-repeat 中允许重复?

javascript - ng-options 默认选项,显示所有选项

javascript - 从 Controller 中为 `<option>` 选择 `<select ng-options>` 值

json - 如何在 ng-options 中显示深度嵌套的 JSON 对象

javascript - 将表达式分配给三元运算符

javascript - "file"对象没有 'path' 属性。 ( typescript )