7

I am trying to build a multiselect list using angular js. I am getting a weird TypeError: a.foreach is not a function and I can’t seem to figure out when.

js :

var myAppModule = angular.module('multiselect', []);

 myAppModule.controller("view", function ($scope) {
$scope.listA = {
    values: [{
        id: 1,
        label: 'aLabel',
        subItem: {
            name: 'aSubItem'
        }
}, {
        id: 2,
        label: 'bLabel',
        subItem: {
            name: 'bSubItem'
        }
}],
    selected: {
        name: 'aSubItem'
    }

};


})

html:

 <select multiple ng-options="item.subItem as item.label for item in listA.values track by item.id" ng-model="listA.selected"></select>

I don’t know what I could be doing wrong. Am I casting something wrong ?

chuck finley
  • 459
  • 3
  • 8
  • 16

3 Answers3

16

The problem is that since you have added the multiple attribute, the value of the select should be an array. So try something similar to this:

$scope.listA = {
    values: [{
        id: 1,
        label: 'aLabel',
        subItem: {
            name: 'aSubItem'
        }
    }, {
        id: 2,
        label: 'bLabel',
        subItem: {
            name: 'bSubItem'
        }
    }],
    selected: [{
        name: 'aSubItem'
    }]

};
danwellman
  • 9,068
  • 8
  • 60
  • 88
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2

You need not to track your values by id. it will do it by default.

<div ng-controller="Main">
    <select multiple ng-options="item.subItem as item.label for item in listA.values" ng-model="listA.selected"></select> 
</div>

JS Fiddle for your code (Fix):

http://jsfiddle.net/juag4okg/

Nikhil Maheshwari
  • 2,198
  • 18
  • 25
1

I was having the same problem. It worked well by creating the static json object as answered above, but did not worked out when i tried to fetched the object or list from the server. Then i realized my server was not sending the json object and i hadn't convert it to json as well. And when i converted it to json it worked perfectly fine.

So if you are having similar problem to display the select options (muliple or single) from the server side data this process might help you.

here is the link to angular angular.toJson() function.

bmnepali
  • 446
  • 11
  • 20