说我有一个对象数组:
var people = [
{name: "person 1", favouriteThing: 'pizza'},
{name: "person 1", favouriteThing: 'vegetables'},
{name: "person 2", favouriteThing: 'spinach'},
{name: "person 2", favouriteThing: 'kimchi'},
];
我希望能够使用select元素优化这些数据,以便第一个元素只包含“人1”和“#1”。和'人2'作为选项(没有重复)。在#1;人1'之后如果选择了,披萨和蔬菜应该在第二个选择元素中可用。
以下是我目前对选择元素的看法:
<select ng-options="person.name for person in people" ng-model="name"></select>
<select ng-options="person.favouriteThing group by name for person in people"></select>
希望对我应采取的方法提出一些意见。也许我应该使用更像这样的物体? (不适合我的情况)
var people = [
{name: "person 1",
favouriteThings: ['pizza', 'vegetables']
},
{name: "person 2",
favouriteThings: ['spinach', 'kimchi']
}
];
答案 0 :(得分:1)
要获得唯一值,请使用undrescore,
$scope.personName =_.uniq(people, function(person) { return person.name; });
答案 1 :(得分:1)
创建了plnkr
你可以有两个解决方案
(1)通过&#39; name&#39;加载单个选择组。属性。
<select ng-options="person.favouriteThing group by person.name for person in c.people" ng-model="name"></select>
(2)加载两个不同的选择。一个有名字,一个有favoriteThing。在更改名称时,您可以加载喜欢的东西。
<select ng-options="person.name for person in c.getPeopleName()" ng-model="personName"></select>
<select ng-options="person.favouriteThing for person in c.getFavoriteThing(personName)" ng-model="favoriteThing"></select>
this.getPeopleName = function () {
return _.uniq(this.people, function (item) {return item.name;})
};
this.getFavoriteThing = function (people) {
var arr = [];
_.each(this.people, function (item) {
if(item.name === people.name) {
arr.push(item);
}
});
return arr;
};