Angularjs - how to get the index of an element in an ng-re-filter in the controller based on the value of one of its properties?

I use ng-repeat in my html file to display the filtered elements:

<li ng-repeat="item in (filteredItems = (items | filter:query))">
  {{ item.name }}
</a>

In the controller, I would like to get the index of an element based on one of its properties.

Accuracy: I would like to get the index in the filtered list , not the entire list.

Here, for example, it will be the index of the element's witch name some_item_7.

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

app.controller('MyCtrl', ['$scope',
  function MyCtrl($scope) {

    $scope.query = 'some';

    $scope.items = 
    [
      { name: 'some_item_1' },
      { name: 'another_item_2' },
      { name: 'some_item_3' },
      { name: 'another_item_4' },
      { name: 'some_item_5' },
      { name: 'another_item_6' },
      { name: 'some_item_7' },
      { name: 'another_item_8' },
      { name: 'some_item_9' }
    ];

    $scope.itemNext = function (item) {
      console.log(item.name);
    };

    $scope.getIndexFromName = function (name) {
      console.log("trying to get the index of the item with name = " + name);
    }

    $scope.getIndexFromName('some_item_7');

  }
]);

http://plnkr.co/edit/C8gL9qV1MyonTwDENO9L?p=preview

Any idea?

+4
source share
1 answer

Your ng-repeat expression creates a filterList array in your scope.
<li ng-repeat="item in (filteredItems = (items | filter:query))">

, , , . $scope.filteredItems

: http://plnkr.co/69nnbaZaulgX0odG7g7Y

: AngularJS - ngRepeat


, , ng-repeat . $filter, . :

$scope.filteredItems = $filter('filter')($scope.items, {name: $scope.query}, false)

ng-repeat filteredItems DOM.

( ) : < 4 >

+7

Source: https://habr.com/ru/post/1531373/


All Articles