我的范围内定义了json,如
$scope.People = [
{
"firstName":"John",
"lastName":"Doe",
"Choices":[
{
"Name":"Dinner",
"Options":[
{
"Name":"Fish",
"ID":1
},
{
"Name":"Chicken",
"ID":2
},
{
"Name":"Beef",
"ID":3
}
]
},
{
"Name":"Lunch",
"Options":[
{
"Name":"Macaroni",
"ID":1
},
{
"Name":"PB&J",
"ID":2
},
{
"Name":"Fish",
"ID":3
}
]
}
]
},
{
"firstName":"Jane",
"lastName":"Doe"
}
];
想要使用angularjs在单个下拉框中列出所有选项选项名称(不重复)。
掉落选项将包含值鱼,鸡肉,牛肉,通心粉,PB& J
<div ng-app="myApp" ng-controller="SomeController">
<select ng-model="people.Choices.Name"
ng-options="people.Choices.Name for people in People"></select>
</div>
但这不起作用。
任何见解都表示赞赏。
答案 0 :(得分:4)
答案 1 :(得分:0)
我这样做是为了更好,但这样的事情呢? Plnkr这是一个开始!
<div ng-repeat="people in People">
<div ng-repeat="choice in people.Choices">
<select ng-model="choice.SelectedOption"
ng-options="option.Name for option in choice.Options"></select>
</div>
</div>
修订版2.现在有选择! Pnkr 2
答案 2 :(得分:0)
好的,我认为您必须对JSON数组进行一些预处理并以此方式对其进行过滤。这是最简单的方法
HTML
<body ng-app="TestApp">
<div ng-controller="TestController">
<select ng-model="blah"
ng-options="opt for opt in options">
</select>
</div>
</body>
JS
var app = angular.module('TestApp',[]);
app.controller('TestController', function($scope)
{
$scope.options = [];
$scope.people = [
{
"firstName": "John",
"lastName": "Doe",
"choices": [
{
"name": "Dinner",
"options": [
{
"name": "Fish",
"id": 1
},
{
"name": "Chicken",
"id": 2
},
{
"name": "Beef",
"id": 3
}
],
"selectedOption": {
"name": "Chicken",
"id": 2
}
},
{
"name": "Lunch",
"options": [
{
"name": "Macaroni",
"id": 1
},
{
"name": "PB&J",
"id": 2
},
{
"name": "Fish",
"id": 3
}
],
"selectedOption": ""
}
]
},
{
"firstName": "Jane",
"lastName": "Doe"
}
];
for (var a = 0; a < $scope.people.length; a++)
{
if ($scope.people[a].choices != undefined)
{
for (var b = 0; b < $scope.people[a].choices.length; b++)
{
for (var c = 0; c < $scope.people[a].choices[b].options.length; c++)
{
var target = $scope.people[a].choices[b].options[c].name;
if ($scope.options.indexOf(target) == -1) $scope.options.push(target);
}
}
}
}
});
我还将一些大写字母修改为全部小写。如果需要,您可以将其更改回来。
答案 3 :(得分:0)
我试图做同样的事情并找到另一个解决方案,只使用ng-if="false"
或style="display: none"
和ng-repeat-start/end
来显示名称。基于@ user730009的回答。
<div ng-repeat="people in People">
<select>
<option ng-repeat-start="choice in people.Choices" ng-if="false"></option>
<option ng-repeat-end ng-repeat="option in choice.Options" value="{{ option.name }}">{{ option.name }}</option>
</select>
</div>
这为我们提供了一个包含以下选项的选择框。