javascript - Angular : ng-repeat. 我如何根据值定位特定项目

标签 javascript angularjs angularjs-ng-repeat

我有 2 组连续加载的数据。

第一个数据将通过 id 定义要重复和跟踪的项目。

items:
    [{"id":21, "name":"john doe"},{"id":15, "name":"john doe"},{"id":13, "name":"john doe"}]

我加载的下一组数据将确定项目的一些状态,由“id”匹配。

[{"idToMatch":15, "status":1},{"idToMatch":13, "status":1}]

我可以通过这样做来重复 dom 项

<div ng-repeat="item in items trackby item.id">
{{item.name}}
</div>

我想做的是将一个类添加到第二个列表中与“idToMatch”匹配到第一个集合的“id”的项目。

最佳答案

我会做什么:

在你的 Controller 中:

//just for example
$scope.matches = [{"idToMatch":15, "status":1},{"idToMatch":13, "status":1}];

$scope.doesItemMatch = function(item) {
   for(var i in $scope.matches) {
      var match = $scope.matches[i];
      if(item.id === match.idToMatch)
        return true;
   }
   return false;
}

然后在你的 html 中:

<div ng-repeat="item in items trackby item.id" ng-class="{yourClass: doesItemMatch(item)}">
  {{item.name}}
</div>

[编辑]:这是一个运行示例

angular.module('test', [])
  .controller('ExampleController', ['$scope',
    function($scope) {
      $scope.items = [{
        "id": 21,
        "name": "john doe"
      }, {
        "id": 15,
        "name": "john doe"
      }, {
        "id": 13,
        "name": "john doe"
      }];
      $scope.matches = [{
        "idToMatch": 15,
        "status": 1
      }, {
        "idToMatch": 13,
        "status": 1
      }];

      $scope.doesItemMatch = function(item) {
        for (var i in $scope.matches) {
          var match = $scope.matches[i];
          if (item.id === match.idToMatch)
            return true;
        }
        return false;
      }
    }
  ]);
.test-class {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="test">
  <div ng-controller="ExampleController">
    <div ng-repeat="item in items" ng-class="{'test-class': doesItemMatch(item)}">
      {{item.name}}
    </div>
  </div>
</body>

关于javascript - Angular : ng-repeat. 我如何根据值定位特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28148681/

相关文章:

javascript - 使用 soundcloud SDK 时未定义“SC”

javascript - 删除数组中的对象元素

angularjs $setValidity 在检查电子邮件唯一性时不起作用

javascript - AngularJS - 当使用切片两次时数据不可用时,ng-repeat 显示空单元格

javascript - 使用 JQuery/JavaScript 下载最新版本的页面?

javascript - 点击ajax中的链接不起作用

javascript - 对每个元素应用自定义 Angular 过滤器

javascript - 计算对象中属性的总持续时间

html - 带有 ng-repeat 的表

javascript - 没有 ng-repeat 的 Angular 过滤器列表