AngularJS filter: find out index of array using AngularJS Filter

212 Views Asked by At

I got this array of data:

$scope.domainRows = [
  { domainName: 'example1.com', domainDescription: 'example1.com desc'},
  { domainName: 'example2.com', domainDescription: 'example2.com desc'},

];

These rows are display as table on UI and user clicks on delete row2 and row2 has this info

{ domainName: 'example2.com', domainDescription: 'example2.com desc'}

Is there anyway that I can use AngularJS filter to get the index of row2? Should have the way to do it in AngularJS filter but couldn't figure out. Need your help. Thanks -k

2

There are 2 best solutions below

0
holydragon On

With pure JavaScript.

const domainRows = [
  { domainName: 'example1.com', domainDescription: 'example1.com desc'},
  { domainName: 'example2.com', domainDescription: 'example2.com desc'}
]
let selectedRow = { domainName: 'example2.com', domainDescription: 'example2.com desc'}
for (let i = 0; i < domainRows.length; i++){
  if (domainRows[i].domainName === selectedRow.domainName){
    console.log(i)
  }
}

The code is in vanilla JavaScript format so that it can run on the snippet for demo. You need to convert it to Angular format to use in your project but it is just a little edit.

2
atefth On

If you are displaying it in a table you can simple pass the $index to the ng-click directive to get the row index like this:

<tr ng-repeat="row in domainRows" ng-click="performAction($index)">
  <td>{{ $index + 1 }}</td>
  <td>{{ row.domainName }}</td>
  <td>{{ row.domainDescription }}</td>
</tr>

If you want to filter the table by the domainName and domainDescription properties then you can do something like this:

<label>Any: <input ng-model="search.$"></label>
<label>Name: <input ng-model="search.domainName"></label>
<label>Description: <input ng-model="search.domainDescription"></label>

<tr ng-repeat="row in domainRows | filter:search" ng-click="performAction($index)">
  <td>{{ $index + 1 }}</td>
  <td>{{ row.domainName }}</td>
  <td>{{ row.domainDescription }}</td>
</tr>