我一直坚持一些简单的事情。我有以下响应JSON:
0
我有一个选择,我需要为shipThruLocationCodes数组中的每个项目显示{
"terminalName": "Montreal",
"shipThruLocationCodes":[
{
"shipThruLocationId": 112,
"shipThruLocationCode": "B84"
}
]
}
,只有一个terminalName。数据存储在名为terminalName (shipThruLocationCode)
的控制器中的数组中。这是我在ng-repeat中尝试过的但是它不起作用:
$scope.shipThrus
我认为我的想法是正确的,但逗号(因为我试图显示两个值)是抛出错误。
总而言之,select应该为每个项目显示以下内容
data-ng-options="shipThru.terminalName for shipThru in shipThrus, item.shipThruLocationCode for item in shipThru.shipThruLocationCodes"
shipThrulocationCodes数组中只有一个终端名称,可以是多个位置代码。
答案 0 :(得分:1)
使用函数生成选项。这是一个向您展示示例的Plunker:
https://plnkr.co/edit/hxlowXWCS6BWh6gGfMMl?p=preview
HTML:
<select ng-model="main.selectedOption" ng-options="option.name for option in main.options"></select>
JS:
var app = angular.module('angularApp', []);
app.controller('MainCtrl', function($scope, $http) {
var vm = this;
vm.terminals = [
{
"terminalName": "Montreal",
"shipThruLocationCodes":[
{
"shipThruLocationId": 112,
"shipThruLocationCode": "B84"
}
]
},
{
"terminalName": "Somewhere else",
"shipThruLocationCodes":[
{
"shipThruLocationId": 113,
"shipThruLocationCode": "B9999"
}
]
}
];
vm.options = [];
generateOptions();
function generateOptions() {
for(var i = 0; i < vm.terminals.length; i++) {
var selectOption = {
name: vm.terminals[i].terminalName + " (" + vm.terminals[i].shipThruLocationCodes[0].shipThruLocationCode + ")"
};
vm.options.push(selectOption);
}
}
});
答案 1 :(得分:0)
检查Plunker http://plnkr.co/edit/Vs2mC9zt3HmO9KGMzV6D?p=preview
如果您将列表设为:
$scope.shipThrus = [{
terminalName: "Montreal",
shipThruLocationCodes: [{
shipThruLocationId: 112,
shipThruLocationCode: "B84"
}, {
shipThruLocationId: 112,
shipThruLocationCode: "B89"
}]
}];
只需创建此功能:
function getLocationCodes(shipThru) {
return shipThru.shipThruLocationCodes.map(function(locationCode) {
return locationCode.shipThruLocationCode;
}).join(', ');
};
将locationCodes
解析为B84, B89
。
然后解析shipThrus
:
$scope.shipThrus.forEach(function(shipThru) {
shipThru.label = shipThru.terminalName + ' (' + getLocationCodes(shipThru) + ')';
});
现在,您可以使用ng-options属性创建select元素:
ng-options="shipThru.shipThruLocationCodes as shipThru.label for shipThru in shipThrus"