Accessing ng-repeat alias expression in controller

1.7k views Asked by At

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?

1

There are 1 answers

0
scniro On

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