Using ng-repeat and filter, how to tell which items are visible?

后端 未结 3 1010
后悔当初
后悔当初 2021-01-04 08:36

I have an array of objects that I\'m displaying in my Angular app using ng-repeat. I\'m filtering out items using filter and the value of a search

相关标签:
3条回答
  • 2021-01-04 09:09

    You can bind the filtered array to another scope variable in your view, then access that in your controller.

    View:

    <tr ng-repeat="item in filteredItems = (items | filter:searchValue)">
      ...
    </tr>
    

    Controller:

    $scope.toggleAll = function () {
      angular.forEach($scope.filteredItems, function (item) {
        // do stuff
      })
    }
    
    0 讨论(0)
  • 2021-01-04 09:10

    Your issue is that ng-repeat is scope isolated. As a result you can't refer to the internal list that is being managed by ng-repeat from your controller/directive.

    As a result there are 2 options

    1. Bind the filtered list to ng-repeat from your controller/directive, so you maintain the filtered list.

      //in your controller
      $scope.filteredItems = $filter('yourFilter')($scope.items,$scope.searchText);
      $scope.$watch('searchText', function(newValue){
         $scope.filteredItems = $filter('yourFilter')($scope.items, newValue);
      });
      
      //in your view
      <tr ng-repeat="item in filteredItems">
          <td>{{item.id}}</td>
          <td>{{item.name}}</td>
      </tr>
      
    2. Perform the filter again in your controller/directive

      $scope.toggleAll() {
          var items = $filter('yourFilter')($scope.items, $scope.searchText);
          for(var i in items){
             //set your selected property
          }
      }
      
    0 讨论(0)
  • 2021-01-04 09:29

    Angular filters create a new array. So in order to perform an action on the filtered items you're going to have to capture the new array.

    Something like:

    $scope.toggleAll() {
      var filteredItems = $filter('filter')($scope.items, $scope.searchValue);
      for(var i in filteredItems) {
        ...
      }
    }
    

    If you don't want to filter twice you'll have to filter the array yourself every time searchValue changes and ng-repeat over that filtered array, ng-change is useful in that case.

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