chuck finley chuck finley - 3 months ago 42
Javascript Question

Getting a a.foreach is not a function error

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 ?

Answer

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'
    }]

};