Getting a.foreach is not a functional error

I am trying to create a list of multi-selections using angular js. I get a weird TypeError: a.foreach is not a function, and I cannot 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 do not know what I can do wrong. Am I doing something wrong?

+7
javascript angularjs
source share
3 answers

The problem is that since you added the multiple attribute, the select value must be an array. So try something like this:

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

You do not need to track your values ​​by id. he 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/

+2
source share

I had the same problem. It worked well by creating a static json object , as mentioned above, but did not work when I tried to retrieve the object or list from the server. Then I realized that my server is not sending a json object , and I did not convert it to json . And when I converted it to json , it worked perfectly.

So, if you have a similar problem to display the selections (multiline or single) from server-side data, this process can help you.

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

+1
source share

All Articles