Shane Shane - 3 months ago 231
AngularJS Question

ng-selected not working 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>


I have an ng-model
dayOfMonth
whose value i am getting as 12, but when i try to select a default value based on
dayOfMonth
its always selecting all the last index.

Below is my
getTotalDays
function which just returns an array of 28 items.

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

Answer

replace this:

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

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

like so:

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>