Millenial2020
Millenial2020

Reputation: 2913

Angular how to have multiple selected

I have this array of objects. that holds somethings like this.

[
    {
        id: 1,
        name: "Extra Cheese"
    },
    {
        id: 2,
        name: "No Cheese"
    }
]

im iterating thru the array here

<select ng-model="item.modifiers" multiple chosen class="chosen-select" tabindex="4" ng-options="modifier._id as modifier.name for modifier in modifiers"></select>

The thing item.modifiers model that has an array of this 2 id

[
    1,2
]

I want the multi select to auto selected the two ids that are in the item.model

I want the final result to look something like this

enter image description here

Upvotes: 0

Views: 2171

Answers (2)

Icycool
Icycool

Reputation: 7179

Your code is pretty much working already, maybe some of the variables are not assigned correctly (eg. id instead of _id)

angular.module('test', []).controller('Test', Test);

function Test($scope) {
  $scope.modifiers = [
    {
        id: 1,
        name: "Extra Cheese"
    },
    {
        id: 2,
        name: "No Cheese"
    }
  ]
  
  $scope.item = {};
  
  // add this for pre-selecting both options
  $scope.item.modifiers = [1,2];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app='test' ng-controller='Test'>
  <select ng-model="item.modifiers" multiple chosen class="chosen-select" tabindex="4" ng-options="modifier.id as modifier.name for modifier in modifiers"></select>
</div>

Upvotes: 1

Andrew Lahikainen
Andrew Lahikainen

Reputation: 370

If I understand the question correctly, you're wanting to pre-select the two options.

To do this you will need to set your ng-model to point to the actual objects you are iterating over.

You will also need to change your ng-options to ng-options="modifier as modifier.name for modifier in modifiers" rather than just iterating over the ids.

Here's the relevant documentation under Complex Models (objects or collections) https://docs.angularjs.org/api/ng/directive/ngOptions

Something like this should work:

HTML:

<select ng-model="$ctrl.item.modifiers"
  ng-options="modifier as modifier.name for modifier in $ctrl.modifiers"
  multiple chosen class="chosen-select" tabindex="4" >
</select>

JS:

app.controller("my-controller", function() {
    var $ctrl = this;

    $ctrl.modifiers = [{
      id: 1,
      name: "Extra Cheese"
    }, {
      id: 2,
      name: "No Cheese"
    }];

    $ctrl.item = {
      modifiers: []
    }

  $ctrl.$onInit = function() {
    const id1 = 1;
    const id2 = 2;
    for (const modifier of $ctrl.modifiers) {
      if (modifier.id === id1 || modifier.id === id2) {
        $ctrl.item.modifiers.push(modifier);
      }
    }
  }
}

Here's a pen showing the result: http://codepen.io/Lahikainen/pen/WooaEx

I hope this helps...

Upvotes: 0

Related Questions