4

I have a filtered list, within a directive:

<div ng-repeat="item in items | filter:filter | limitTo:5 as filteredItems">
    <div ng-bind="item.title"></div>
</div>
<div><span ng-bind="filteredItems.length"></span> items</div>

I wish to access and manipulate the filtered list in the directive's controller. However scope.filteredItems is undefined in the controller.

How can I pass the filtered array to the directive's controller?

scniro
  • 16,844
  • 8
  • 62
  • 106
Adamski
  • 3,585
  • 5
  • 42
  • 78
  • 1
    check out this thread http://stackoverflow.com/questions/30718300/using-ng-repeat-and-filter-how-to-tell-which-items-are-visible/30718588#30718588 – allienx Jun 09 '15 at 16:13
  • Have you made any progress on this? Was my suggestion able to help you? – scniro Jun 11 '15 at 00:49
  • @salniro the issue is on hold while we work on some other stuff... will probably pick it up again next week. – Adamski Jun 12 '15 at 13:40
  • @Adamski any progress on this? Could you check out my suggestion and see if it works? You can always check out the fiddle then implement this in your specific scenario when you find convenient. I would like to see this question get resolved – scniro Jun 22 '15 at 16:35

1 Answers1

2

You'll be able to get a hold of your filtered array by injecting $filter into your controller and leveraging the following, targeting your custom filter of filter

$scope.filteredItems = $filter('filter')($scope.items)

This will include your new array with both filters of filter and limitTo applied. Observe the simplistic example to demonstrate this

<span ng-bind="filteredItems.length"></span><!-- 2 -->
<div class="item" ng-repeat="item in items | filter | limitTo: 2 as filteredItems"></div>

app.filter('filter', function() {
    return function(input) {
        return input.slice(0, 4); // 4 items - initial filter
   };
})

app.controller('ctrl', ['$scope', '$filter', function($scope, $filter) {
    $scope.items = [
        {'key': 'A', 'value': 0},
        {'key': 'B', 'value': 1},
        {'key': 'C', 'value': 2},
        {'key': 'D', 'value': 3},
        {'key': 'E', 'value': 4},
        {'key': 'F', 'value': 5},
        {'key': 'G', 'value': 6},
        {'key': 'H', 'value': 7}
    ];

    $scope.filteredItems = $filter('filter')($scope.items) // 2 items - compound filter
}]);

JSFiddle Link - working example

scniro
  • 16,844
  • 8
  • 62
  • 106