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
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
})
}
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
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>
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
}
}
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.