Question

If I want to set the value of the combobox I have tried this:

controllercode:

 $scope.streettypeMockData = [{
    name: 'Street',
    value: 'Street'
  }, {
    name: 'Avenue'
  }, {
    name: 'Crescent'
  }, {
    name: 'Drive'
  }, {
    name: 'Road'
  }, {
    name: 'Highway'
  }];

  var sel = "Street";
  var selectedValue = {
    name: sel
  };
  $scope.streetTypeSelected = selectedValue;

Can anyone tell me why this does not work? see also http://plnkr.co/edit/4ISL8A1cNGCtafsc0leX?p=preview

Était-ce utile?

La solution

The code has a few issues:

  • The ng-options select the name, while the ng-model points to an object. Better use streetType as streetType.name for streetType in streettypeMockData to select the entire object.
  • In this case, the initial value will not be honoured because Angular will try to compare objects by reference; use track by.

The full <select> should be:

    <select class="form-control" ng-model="streetTypeSelected"
      ng-options="streetType as streetType.name for streetType in streettypeMockData track by streetType.name">

See forked plunker.

Autres conseils

You can simple use ng-init like this

<select ng-init="streetTypeSelected = streettypeMockData[0]" class="form-control" ng-model="streetTypeSelected" ng-options="streetType.name for streetType in streettypeMockData">
  </select>

Working Demo

Also you can do Like as shown below

var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
     $scope.streettypeMockData = [
        {name: 'Street', value: 'Street'},
        {name: 'Avenue'},
        {name: 'Crescent'},
        {name: 'Drive'},
        {name: 'Road'},
        {name: 'Highway'}
    ];
    $scope.streetTypeSelected = $scope.streettypeMockData[0];
});

Working Demo

Also take a look at this

https://docs.angularjs.org/api/ng/directive/select

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top