问题
I have a form with select boxes to choose a business' working hours. I want to choose 9:00 am as the default value for the first box, and 5:00 pm as the default value for the second box.
Here is the JSfiddle
For example, I have
<select ng-options="hour as (hour | date: 'shortTime') for hour in hours"
ng-model="start_time" ng-change="update(start_time, $index, 1)">
If in my app.js I set $scope.start_time
equal to a Date object initialized to the current date and time as 9:00 am, the default value is chosen as the last value in the select box instead. Since I am using a date filter to display the time in the select box in the 'shortTime' format, is that the reason why the default value is not being shown correctly?
回答1:
Just set the model start_time
right, for example in your controller!
<select ng-options="hour as (hour | date: 'shortTime') for hour in hours track by hour"
ng-model="start_time" ng-change="update(start_time, $index, 1)">
$scope.start_time = new Date(); // set default date in controller
Using the latest angular version and track by hour
solves the problem: http://jsfiddle.net/j8xu1h2h/
来源:https://stackoverflow.com/questions/32999234/how-to-choose-default-time-value-in-a-select-box-with-ng-options