Mikhail Kostiuchenko
Mikhail Kostiuchenko

Reputation: 10541

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

Upvotes: 0

Views: 282

Answers (3)

Barremian
Barremian

Reputation: 31125

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>

Upvotes: 0

palaѕн
palaѕн

Reputation: 73966

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;

Upvotes: 1

Bill P
Bill P

Reputation: 3618

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

Upvotes: 1

Related Questions