我目前正在尝试构建具有复杂数据结构的AngularJS应用程序。
数据源是一组具有语言和技能水平的人。 我需要通过语言技能来过滤这些人,为此我尝试使用语言建立一个选择,并使用技能级别建立另一个选择,但我失败了。
也许还有一种更简单/更好的方法来构建数据数组($ scope.people)
答案 0 :(得分:1)
看看这个
<强> Working Demo 强>
<强> HTML 强>
<div ng-app='myApp' ng-controller="MainCtrl">LANGUAGES:
<select ng-model="selectLang" ng-options="lang as lang for lang in languages"></select>
<br>SKILL:
<select ng-model="selectSkill" ng-options="skill as skill for skill in skills"></select>
<br>
<button ng-click="getPeople()">Submit</button>
<br>PEOPLE:
<select ng-model="selectPeoples" ng-options="people as people for people in peoples"></select>
</div>
<强>脚本强>
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope) {
$scope.people = [{
"name": "Jane Doe",
"gender": "Female",
"languages": [{
"lang": "German",
"skill": "Good"
}, {
"lang": "English",
"skill": "Very Good"
}]
}, {
"name": "John Doe",
"gender": "Male",
"languages": [{
"lang": "French",
"skill": "Good"
}, {
"lang": "English",
"skill": "Very Good"
}]
}];
$scope.languages = [];
$scope.skills = [];
angular.forEach($scope.people, function (peopleValue, peopleKey) {
angular.forEach(peopleValue.languages, function (langValue, langKey) {
$scope.languages.push(langValue.lang);
$scope.skills.push(langValue.skill);
});
});
$scope.languages = _.uniq($scope.languages);
$scope.skills = _.uniq($scope.skills);
$scope.getPeople = function () {
$scope.peoples = [];
angular.forEach($scope.people, function (peopleValue, peopleKey) {
angular.forEach(peopleValue.languages, function (langValue, langKey) {
if (langValue.lang === $scope.selectLang && langValue.skill === $scope.selectSkill) {
$scope.peoples.push(peopleValue.name);
}
});
});
}
});
答案 1 :(得分:1)
您的问题是,您实际上并没有遍历languages
指令中每个人的ng-options
数组。鉴于您的数据结构如何,我认为实际上并不存在这样的事情。我不认为你可以遍历嵌套数组(或者至少我不知道任何允许这样的ng-options
语法。
为了简化操作,我建议您在控制器中执行以下操作:
$scope.langs = [];
angular.forEach($scope.people, function(person){
angular.forEach(person.languages, function(lang){
$scope.langs.push({
lang: lang.lang,
skill: lang.skill,
name: person.name,
gender: person.gender
});
});
});
这将为您提供一个数组,允许您使用带有`orderBy'过滤器的ng-options
进行过滤。