简体   繁体   中英

Selecting `<option>` value from controller for `<select ng-options>`

<select
      class="form-control input-md
      availabiltyDatesInput pull-left"
      name="statusModel"
      autocomplete="off"
      id="statusModel"
      ng-options="alertStatus.value as alertStatus.text for alertStatus in alertStatuses"
      ng-model="statusModel">
 </select>

I have a Select with options. And I need that the value of this select will be pre populated.

I'm trying to set ng-model in controller:

angular.module("app.alerts")
.controller("alertsCtrl", function ($scope, CarmateCommonApiSvc, $uibModal) {

     getLookupsData();

     var alertStatuses = [];

     function getLookupsData() {
        alertStatuses = [];

        CarmateCommonApiSvc.getLookups().then(function (res) {
            if (res.code != 0) return;
            _.each(res.data.allLookups, function (item, index, arr) {

                if(item.name == 'AlertStatus'){
                    alertStatuses.push(item);
                }
            });
            $scope.alertStatuses = alertStatuses;                
            $scope.statusModel = alertStatuses[0];
        })
     }
});

But it doesn't work. I'm new in AngularJs

You need to set the ng-model with the value like this:

$scope.statusModel = alertStatuses[0].value;

For more information and examples check here: link

Maybe you should check first if the array has any items:

if(alertStatuses.length > 0){
    $scope.statusModel = alertStatuses[0].value;
}

statusModel should only be set as a single vale not the full object alertStatuses[0] . So, update your code like:

$scope.statusModel = alertStatuses[0].value || 0;

You could actually abuse ng-init directive.

<select
  class="form-control input-md availabiltyDatesInput pull-left"
  name="statusModel"
  autocomplete="off"
  id="statusModel"
  ng-options="alertStatus.value as alertStatus.text for alertStatus in alertStatuses"
  ng-model="statusModel"
  ng-init="statusModel = alertStatuses[0]"
>
</select>

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