简体   繁体   中英

Angular always selects the first option in select element

So this is my select (I'm not using the ng-options feature as I need to disable options and I'm using angular 1.3.x, disable by feature is in 1.4 afaik)

<select class="checkout" 
        ng-model="user.deliveryTime" 
        ng-change="timeUpdate  = true"
        ng-class="{'selected' : user.deliveryTime}" >
  <option value="" disabled selected>Delivery Slot </option>
  <option ng-repeat = "deliveryTime in intervals" 
          ng-disabled="deliveryTime.tooLate" value="{{deliveryTime.time}}">
       {{deliveryTime.time}}
   </option>
</select>

Here's how preselect a value for the select

config.deliveryTimes(function(m){
  $scope.intervals = m;
  $scope.user.deliveryTime = $scope.intervals[2].time;
});

config.deliveryTimes(callback) basically makes a HTTP request and back.

Even when I explicitly set the option of the 3rd value of the array, I always get the first option. When I hard-code the options in the select's controller, it still doesn't work.

Any help?

Remove the selected attribute on the default option and use ng-selected="user.deliveryTime === deliveryTime.time" :

<select class="checkout" 
        ng-model="user.deliveryTime" 
        ng-change="timeUpdate  = true"
        ng-class="{'selected' : user.deliveryTime}" >
  <option value="" disabled>Delivery Slot </option>
  <option ng-repeat = "deliveryTime in intervals" 
          ng-disabled="deliveryTime.tooLate" value="{{deliveryTime.time}}"
          ng-selected="user.deliveryTime === deliveryTime.time">
       {{deliveryTime.time}}
   </option>
</select>

When you use ng-value instead of value in the option, the selected option is bind to the options set in the ng-model (user.deliverytime)

<select class="checkout" 
    ng-model="user.deliveryTime" 
    ng-change="timeUpdate  = true"
    ng-class="{'selected' : user.deliveryTime}" >
<option value="" disabled>Delivery Slot </option>
<option ng-repeat = "deliveryTime in intervals" 
        ng-disabled="deliveryTime.tooLate" ng-value="deliveryTime.time"
        >
     {{deliveryTime.time}}
 </option>

http://plnkr.co/edit/8hKIXwK5i35lczWEtuCw?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM