Using indexOf() to search array inside ng-repeat

475 views Asked by At

I'm try to search an array of id's [1, 2, 3] with indexOf() inside an ng-repeat loop, but probably because of a wrong data type, it doesn't work.

<li ng-repeat="member in message.members">
    Member ID: {{ member.id }}
    <span ng-if="message.read_by.indexOf(member.id) > -1">Read</span>
</li>

The array message.read_by = [1, 2, 3] and member.id = 1 printed correct for each member inside the loop, but the message.read_by.indexOf(member.id) > -1 always returns false.

If i replace the member.id with message.read_by.indexOf(1) > -1 returns true.

I tried to pass the member.id on parseInt() or toString() because it looks to me as a problem because a wrong data type but that doesn't work also.

What's the correct method i should use to pass the member.id value?

2

There are 2 answers

1
Arun P Johny On BEST ANSWER

The problem here is the data type of the values, the read_by array has int values where as member.id is string.

One easy fix is

var app = angular.module('my-app', [], function() {})

app.controller('AppController', function($scope) {
  $scope.isRead = function(member) {
    return $scope.message.read_by.indexOf(+member.id) > -1;
  }
  $scope.message = {
    read_by: [1, 2, 3],
    members: [{
      id: "1"
    }, {
      id: "3"
    }, {
      id: "5"
    }]
  };
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="my-app" ng-controller="AppController">
  <ul>
    <li ng-repeat="member in message.members">
      Member ID: {{ member.id }}
      <span ng-if="isRead(member)">Read</span>
    </li>
  </ul>
</div>

1
Peanut On

You can use track by $index for this purpose:

<li ng-repeat="member in message.members track by $index">
    Member ID: {{ member.id }}
    <span ng-if="$index > 1">Read</span>
</li>

Have a look at the documentation for more information.