ng-selected not working angularjs

时间:2016-08-11 13:59:47

标签: javascript angularjs

<select ng-model="dayOfMonth">
   <option value="" label="Select day"></option>
   <option ng-selected="parseInt(dayOfMonth) === parseInt(day+1)"  ng-repeat="day in getTotalDays() track by $index" value="{{$index+1}}>{{$index+1 | ordinal}} of the month</option>
</select>

我有一个ng-model dayOfMonth,其值为12,但是当我尝试选择基于dayOfMonth的默认值时,它总是选择所有最后一个索引。

下面是我的getTotalDays函数,它只返回28个项目的数组。

$scope.getTotalDays = function(){
   return new Array(28);
}

2 个答案:

答案 0 :(得分:2)

替换这个:

<select ng-model="dayOfMonth">
   <option value="" label="Select day"></option>
   <option ng-selected="parseInt(dayOfMonth) === parseInt(day+1)"  ng-repeat="day in getTotalDays() track by $index" value="{{$index+1}}>{{$index+1 | ordinal}} of the month</option>
</select>

ng-options https://docs.angularjs.org/api/ng/directive/ngOptions

像这样:

angular.module('myApp', [])
  .controller('myController', ['$scope',
    function($scope) {
      $scope.getTotalDays = [1, 2, 3, 5];
    }
  ]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="myController">
    <select ng-model="dayOfMonth" ng-options="day as (day + ' of the month') for day in getTotalDays">
      <option value="" label="Select day"></option>
    </select>
  </div>
</div>

答案 1 :(得分:1)

您无需使用ng-selected,因为<select>中的正确选项将由ng-model设置。您可能遇到的一个问题是,如果您设置dayOfMonth = 12,因为它是一个int,但选项值都是字符串。下面的代码段有效但我必须删除| ordinal过滤器,因为您没有提供该代码。

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.dayOfMonth = '12';
    $scope.getTotalDays = function() {
      return new Array(28);
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <select ng-model="dayOfMonth">
    <option value="" label="Select day"></option>
    <option ng-repeat="day in getTotalDays() track by $index" value="{{$index+1}}">{{$index+1}} of the month</option>
  </select>
</div>