0
<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);
}
3
  • 2
    Theres a missing " after the value Commented Aug 11, 2016 at 14:02
  • jsfiddle.net/x0n0gous it does not work.. Commented Aug 11, 2016 at 14:31
  • @Shane, is there a reason to not use ngOptions (the directive that was made exclusively for <select> tag)? Commented Aug 11, 2016 at 23:43

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to use ng-selected because the proper option in your <select> will be set by ng-model. One possible issue you may have had is if you are setting dayOfMonth = 12 since it is an int, but the option values are all strings. The below snippet works although I had to remove the | ordinal filter since you didn't provide that code.

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.