角度属性(变量)在视图中使用

时间:2015-04-01 17:44:42

标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

我有一份学校名单和一份教师名单。

学校

    [
    {
    "id": 1,
    "nameOfInstitution": "Summer Elementary",
    "schoolLevel": "01304"
    },
    {
    "id": 2,
    "nameOfInstitution": "Grady Middle",
    "schoolLevel": "02400"
    }
    ]

教师

[
{
  "id": "1",
  "school": "1",
  "name": {
    "lastOrSurname": "HARRISON",
    "firstName": "JOHN",
    "middleName": ""
  }
},
{
  "id": "2",
  "school": "1",
  "name": {
    "lastOrSurname": "Nelson",
    "firstName": "Darren",
    "middleName": ""
  }
},
{
  "id": "3",
  "school": "2",
  "name": {
    "lastOrSurname": "Stewart",
    "firstName": "Manuel",
    "middleName": ""
  }
}]

在控制器中我有 ...

$scope.schools = schools;
$scope.teachers = teachers;

问题与观点有关。我怎样才能做到这一点?

  • 夏季小学
    • JOHN HARRISON
    • Darren Nelson
  • 格雷迪中
    • Manuel Steward

我一直在使用“ng-repeat”指令,但我怎样才能只展示属于每所学校的老师呢?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以过滤ng-repeat中的教师:

<div ng-repeat="school in schools">
  <div ng-repeat="teacher in teachers | filter: {school: school.id}">

但请务必为教师使用的每所学校添加id属性。

或者如果teacher.school属性是学校阵列中的学校索引,您可以这样做:

<div ng-repeat="school in schools">
  <div ng-repeat="teacher in teachers | filter: {school: $index}">

最后一点:这会有效但是如果你有很多学校和老师,那么在你展示它之前从javascript执行过滤会更有效率,即构建像

这样的结构
schools = [{
  nameOfInstitution: ...,
  schoolLevel: ...,
  teachers: [{
    lastOrSurname: ...
  }]
  // ... etc
}];

答案 1 :(得分:0)

使用过滤器:

<div ng-repeat="school in schools">
  {{school.nameOfInstitution}}
<p ng-repeat="teacher in teachers | filter:{school: ''+ ($index+1)}:true">
  {{teacher.name.lastOrSurname}}
</p>
</div>

但你最好为学校提供某种身份证明......