首页 > 解决方案 > 匹配两个 ng-repeats 的对象属性

问题描述

使用 AngularJS,我使用了两个ng-repeats 和与ng-if. 第一个ng-repeat使用对象数组循环近 250 个对象,例如:

[{
  "Title": "First1 Last1",
  "FirstName": "First1",
  "LastName": "Last1",
  "ID": 29
}, {
  "Title": "First2 Last2",
  "FirstName": "First2",
  "LastName": "Last2",
  "ID": 25
}]

第二个ng-repeat循环对象数组中的近 4600 个对象,类似于:

[{
  "ParentUserLink": {
    "ID": 25
  },
  "Title": "USER2",
  "InitialPassword": "Already Received",
}, {
  "ParentUserLink": {
    "ID": 29
  },
  "Title": "USER1",
  "InitialPassword": "Asdf1234",
}, {
  "ParentUserLink": {
    "ID": 25
  },
  "Title": "USER2",
  "InitialPassword": "Already Received",
}, {
  "ParentUserLink": {
    "ID": 25
  },
  "Title": "USER2",
  "InitialPassword": "Already Received",
}]

使用ng-repeat="app in apps" ng-if="app.ParentUserLink.ID == user.ID"允许我在应用程序属于正确的用户时显示它们。但是,这可能需要几分钟才能加载,并且经常会使浏览器崩溃。什么是更有效的方法?

我的 HTML:

<div ng-repeat="user in users" id="pagebreak">
  <div class="ProfileSheet">
    <h3 class="heading" style="border-top: 3px solid #707070;">User Profile</h3>
    <table id="Profile" style="border-top: 3px solid #707070;">
      <tr>
        <th>User</th>
        <td>{{user.Title}}</td>
      </tr>
      <tr>
        <th>First Name</th>
        <td>{{user.FirstName}}</td>
      </tr>
      <tr>
        <th>Last Name</th>
        <td>{{user.LastName}}</td>
      </tr>
    </table>
    <br>

    <h3 class="heading">User Applications</h3>
    <div style="border:3px solid #707070; padding-right:12px;">
      <h4 style="padding-left:5px;">User Applications</h4>
      <table id="Apps">
        <tr id="AppsHeading">
          <th>User ID</th>
          <th>Initial Password</th>
        </tr>
        <tr ng-repeat="app in apps" ng-if="app.ParentUserLink.ID == user.ID">
          <td>{{app.Title}}</td>
          <td>{{app.InitialPassword}}</td>
        </tr>
      </table>
    </div>

  </div>
</div>

标签: javascripthtmlarraysangularjs

解决方案


ng-repeat在表达式中使用过滤器:

̵<̵t̵r̵ ̵n̵g̵-̵r̵e̵p̵e̵a̵t̵=̵"̵a̵p̵p̵ ̵i̵n̵ ̵a̵p̵p̵s̵"̵ ̵n̵g̵-̵i̵f̵=̵"̵a̵p̵p̵.̵P̵a̵r̵e̵n̵t̵U̵s̵e̵r̵L̵i̵n̵k̵.̵I̵D̵ ̵=̵=̵ ̵u̵s̵e̵r̵.̵I̵D̵"̵>̵
<tr ng-repeat="app in apps | filter : idFilter(user.ID)">
  <td>{{app.Title}}</td>
  <td>{{app.InitialPassword}}</td>
</tr>

JS

$scope.idFilter = function(id) {
    return filter;
    function filter(value, index, array) {
         return value.ParentUserLink.ID == id;
    }
};

这避免了将ng-if指令与其关联的子范围和观察者一起使用。


推荐阅读