Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
692 views
in Technique[技术] by (71.8m points)

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 a ng-repeat in my html file to display filtered items:

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

In the controller, I'd like to get the index of an item based on one of his property.

Precision: I'd like to get the index in the filtered list and not in the whole list.

Here for example, it will be the index of the item witch name is 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

You can loop through it like any array, checking for the item matching the name parameter. $scope.filteredItems

Here is a demo: http://plnkr.co/69nnbaZaulgX0odG7g7Y

See this related post: AngularJS - how to get an ngRepeat filtered result reference

Update
Your comments indicate that you don't want to wait for ng-repeat to create the array of filtered items. You can use the $filter service to easily initialize the same array before the page loads. Use:

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

Doing so does not interfere with ng-repeat saving its filter results to the same filteredItems array during DOM creation.

Here is an updated (and interactive) demo: http://plnkr.co/NSvBz1yWvmeFgXITutZF


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...