我有这样的数据结构:
$scope.classes = [
{Dept:'Science', Class:'101'},
{Dept:'Science', Class:'102'},
{Dept:'Science', Class:'103'},
{Dept:'Arts', Class:'111'},
{Dept:'Arts', Class:'112'},
{Dept:'Arts', Class:'113'}];
$scope.professors = [
{Dept:'Science', Class:null, Name:'John Smith'},
{Dept:'Science', Class:'101', Name:'Eric Doe'},
{Dept:'Arts', Class:null, Name:'Mary Smith'},
{Dept:'Arts', Class:'111', Name:'Frank Moore'}
]
当部门和班级都匹配时,我想展示教授的名字。如果没有,请显示该部门的教授姓名(Class = null)。
但是,我的结果如下:
Dept:Science Dept:Science Dept:Science Dept:Arts Dept:Arts Dept:Arts
Class:101 Class:102 Class:103 Class:111 Class:112 Class:113
John Smith John Smith John Smith Mary Smith Mary Smith Mary Smith
Eric Doe Frank Moore
如何使结果如下:
Dept:Science Dept:Science Dept:Science Dept:Arts Dept:Arts Dept:Arts
Class:101 Class:102 Class:103 Class:111 Class:112 Class:113
Eric Doe John Smith John Smith Frank Moore Mary Smith Mary Smith
这是我的fiddle
答案 0 :(得分:0)
感谢 @ water42 提供可能解决方案的想法。
我尝试了它并且有效。
function TodoCtrl($scope) {
$scope.classes = [
{Dept:'Science', Class:'101'},
{Dept:'Science', Class:'102'},
{Dept:'Science', Class:'103'},
{Dept:'Arts', Class:'111'},
{Dept:'Arts', Class:'112'},
{Dept:'Arts', Class:'113'}];
$scope.professors = [
{Dept:'Science', Class:null, Name:'John Smith'},
{Dept:'Science', Class:'101', Name:'Eric Doe'},
{Dept:'Arts', Class:null, Name:'Mary Smith'},
{Dept:'Arts', Class:'111', Name:'Frank Moore'}
];
$scope.classes = $scope.classes.map(function(roomClass) {
var professor_count = $scope.professors.filter(function(professor) {
return professor.Class === roomClass.Class;
});
roomClass.hasProfessor = professor_count.length > 0;
return roomClass;
});
console.log($scope.classes);
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div ng-app>
<div ng-controller="TodoCtrl">
<table>
<tr>
<th width="10%" ng-repeat="class in classes track by $index">
Dept:{{class.Dept}} <br/>
Class:{{class.Class}}
</th>
</tr>
<tr>
<td width="10%" ng-repeat="class in classes track by $index">
<div ng-repeat="prof in professors" ng-if="prof.Dept === class.Dept">
<div ng-if="class.hasProfessor && prof.Class === class.Class">
{{prof.Name}}
</div>
<div ng-if="!class.hasProfessor && prof.Class === null">
{{prof.Name}}
</div>
</div>
</td>
</tr>
</table>
</div>
</div>
&#13;