angularjs - how to get in the controller the index of an item in a ng-repeat filter based on the value of one of its properties? -
i use ng-repeat in html file display filtered items:
<li ng-repeat="item in (filtereditems = (items | filter:query))"> {{ item.name }} </a> in controller, i'd index of item based on 1 of property.
precision: i'd index in filtered list , not in whole list.
here example, index of item 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 index of item name = " + name); } $scope.getindexfromname('some_item_7'); } ]); http://plnkr.co/edit/c8gl9qv1myontwdeno9l?p=preview
any idea ?
your ng-repeat expression creates filteredlist array on scope.
<li ng-repeat="item in (filtereditems = (items | filter:query))">
you can loop through array, checking item matching name parameter. $scope.filtereditems
here demo: http://plnkr.co/69nnbazaulgx0odg7g7y
see related post: angularjs - how ngrepeat filtered result reference
update
comments indicate don't want wait ng-repeat create array of filtered items. can use $filter service initialize same array before page loads. use:
$scope.filtereditems = $filter('filter')($scope.items, {name: $scope.query}, false) doing not interfere ng-repeat saving filter results same filtereditems array during dom creation.
here updated (and interactive) demo: http://plnkr.co/nsvbz1ywvmefgxitutzf
Comments
Post a Comment