CaffeineShots
CaffeineShots

Reputation: 2162

Angular selected for multiple select

I'm working on this fiddle HERE

this is my controller

angular.module('demoApp', []).controller('DemoController', function($scope) {

  $scope.options = [
    { label: 'one', value: 'a' },
    { label: 'two', value: 'b' },
    { label: 'three', value: 'c' },
    { label: 'four', value: 'd' }
  ];

  $scope.selected = [{ 'sel': 'a' },{ 'sel': 'b' },{ 'sel': 'c' } ] ;


});

the $scope.options is the option for my select dom and the $scope.selected is the selected item in my select dom

this is my index.html

<body ng-app="demoApp">
    <div ng-controller="DemoController">
        <div ng-repeat="data in selected">
            <select ng-model="data.sel"
                ng-options="opt as opt.label for opt in options">
            </select>
            selected must be : {{data.sel}}
        </div>
    </div>
</body>

what I had is this

enter image description here

what I need is on first load the selected must be selected like this

enter image description here

could anyone help me?

Upvotes: 1

Views: 101

Answers (2)

huan feng
huan feng

Reputation: 8623

You can use ngInit for default:

<body ng-app="demoApp">
    <div ng-controller="DemoController">
        <div ng-repeat="data in selected">
            <select ng-model="data.sel"
            ng-options="opt.value as opt.label for opt in options" ng-init="data.sel = data.sel || options[$index].value">
        </select>
            selected must be : {{data.sel}}
        </div>
    </div>
</body>

fiddle

Upvotes: 2

DonJuwe
DonJuwe

Reputation: 4563

You could use ng-init to select the ng-model value by their $index:

<select ng-model="data.sel" ng-options="opt as opt.label for opt in options" ng-init="data.sel = options[$index]"></select>

Updated your Fiddle.

Upvotes: 0

Related Questions