在角度ng-repeat中比较两个对象数组

时间:2018-08-30 22:04:47

标签: angularjs

我正在尝试比较两个对象数组,并选中一个具有相同对象的复选框。 下面是对象数组

objArray1 = [
    {b: "AAA", c: 555, d:"RRR", e:"YYY"},
    {b: "WWW", c: 985, d:"DDD", e:234},
    {b: 675, c: 555, d:"RRU", e:"SSS"},
    {b: "TTT", c: 905, d:"PPP", e:"GGG"}
    ]
objArray2 = [
    {b: "AAA", c: 555, d:"RRR", e:"YYY"},
    {b: "TTT", c: 905, d:PPP", e:"GGG"}
    ]

我尝试使用angular.equals,但无法正常工作。有没有一种方法可以做到这一点?

<tr ng-repeat="objs in objArray1 ">
  <td>{{objs}}</td>
  <td>
      <input type="checkbox" id="{{$index}}" 
             ng-checked="angular.equals(objArray1,objArray2)" />
  </td>
</tr>

任何解决方案

1 个答案:

答案 0 :(得分:0)

创建一个在视图中使用的辅助函数,该函数将检查给定对象是否在第二个数组中。

var app = angular.module('app', []);

app.controller('ctrl', function() {
  var $ctrl = this;

  $ctrl.objArray1 = [
    {b: "AAA", c: 555, d:"RRR", e:"YYY"},
    {b: "WWW", c: 985, d:"DDD", e:234},
    {b: 675, c: 555, d:"RRU", e:"SSS"},
    {b: "TTT", c: 905, d:"PPP", e:"GGG"}
  ]

  $ctrl.objArray2 =[
    {b: "AAA", c: 555, d:"RRR", e:"YYY"},
    {b: "TTT", c: 905, d:"PPP", e:"GGG"}
  ]

  $ctrl.isInArray = function(obj, objArray) {
    return objArray.findIndex((el) => {
      return angular.equals(obj, el);
    }) >= 0;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl as $ctrl">
  <table>
    <tr ng-repeat="objs in $ctrl.objArray1">
      <td>{{objs}}</td>
      <td><input type="checkbox" id="{{$index}}" ng-checked="$ctrl.isInArray(objs, $ctrl.objArray2)" /></td>
    </tr>
  </table>
</div>