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?

后端 未结 1 493
走了就别回头了
走了就别回头了 2020-12-06 08:18

I use a ng-repeat in my html file to display filtered items:

  • {{ item.name }} <
  • 相关标签:
    1条回答
    • 2020-12-06 08:52

      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

      0 讨论(0)
    提交回复
    热议问题