javascript 获取 a.foreach 不是函数错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32174145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting a a.foreach is not a function error
提问by chuck finley
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.
我正在尝试使用 angular js 构建多选列表。我收到一个奇怪的 TypeError: a.foreach is not a function,我似乎无法弄清楚什么时候。
js :
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:
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 ?
我不知道我可能做错了什么。我是不是有什么问题?
回答by Arun P Johny
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:
问题在于,由于您添加了multiple
属性,因此选择的值应该是一个数组。所以尝试类似的事情:
$scope.listA = {
values: [{
id: 1,
label: 'aLabel',
subItem: {
name: 'aSubItem'
}
}, {
id: 2,
label: 'bLabel',
subItem: {
name: 'bSubItem'
}
}],
selected: [{
name: 'aSubItem'
}]
};
回答by Nikhil Maheshwari
You need not to track your values by id. it will do it by default.
您无需通过 id 跟踪您的值。默认情况下它会这样做。
<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):
JS Fiddle 为您的代码(修复):
回答by bmnepali
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.
我遇到了同样的问题。通过json object
按照上面的回答创建静态效果很好,但是当我尝试从服务器获取对象或列表时没有解决。
然后我意识到我的服务器没有发送json object
,我也没有将其转换json
为。当我将它转换为它时,json
它工作得很好。
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.
这是角度angular.toJson()
函数的链接。