Reputation: 5687
<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);
}
Upvotes: 0
Views: 631
Reputation: 7194
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>
Upvotes: 1
Reputation: 2829
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>
Upvotes: 2