2

In my angular app, I have a bootstrap multiple select. When i do not give an ng-model attribute, it works as expected.

<select name="sample" class="form-control" multiple>
     <option 
            ng-repeat="item in vm.items" 
            value="{{item.id}}" 
            selected>
            {{item.name}} 
     </option>
</select>

This selects all the available options.

But I provide an ng-model, only the last value gets selected.

<select name="sample" class="form-control" multiple ng-model="someModel">
     <option 
            ng-repeat="item in vm.items" 
            value="{{item.id}}" 
            selected>
            {{item.name}} 
     </option>
</select>

Am I missing something here?

3
  • And what is the value of the model someModel? Commented Dec 9, 2015 at 7:22
  • Empty as in empty object {} ? or not assigned/undefined Commented Dec 9, 2015 at 7:28
  • Use ng-options instead of ng-repeat Commented Dec 9, 2015 at 7:30

1 Answer 1

2

You should not manually render options with ngRepeat. Use ngOptions directive for this:

<select name="sample" class="form-control" multiple 
    ng-options="item.id as item.name for item in vm.items"
    ng-model="vm.someModel">
</select>   

Now, in order to make all options selected you need to populate vm.someModel with corresponding ids. So in controller you could do:

this.someModel = this.items.map(function(item) {
    return item.id;
});

Check the demo below.

angular.module('demo', []).controller('MainCtrl', function($scope) {
    this.items = [{name:'One', id:1}, {name: 'Two', id: 2}, {name: 'Three', id:3}];
    this.someModel = this.items.map(function(item) {
        return item.id;
    });
});
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>


<div ng-app="demo" ng-controller="MainCtrl as vm">
    <select name="sample" class="form-control" multiple 
        ng-options="item.id as item.name for item in vm.items"
        ng-model="vm.someModel">
    </select>   
    
    {{ vm.someModel }} 
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.