0

I'm trying to compare two object arrays and check a checkbox for those that have the same object. below are the object array

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"}
    ]

I tried using angular.equals but it's not working. Is there a way to do this in the view?

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

Any solution

1
  • have you tried declaring a function on the $scope which runs the angular.equals check for you and then using the value as the expression for the ng-checked? by having an onclick handler somewhere to execute the function? e.g $scope.compare = function() { $scope.result = angular.equals(objArray1, objArray2); }; as per AngularJs docs. Commented Aug 30, 2018 at 22:17

1 Answer 1

1

Create a helper function to use in view that will check if given object is in the second array.

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.