javascriptangularjsng-options

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


Solution

  • 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;
    }