I've been searching and fiddling with this for about a day now with no luck. I have a site using AngularJS 1.3.6 where I need to get the results of a filter outside of several nested ng-repeats. I'm filtering the rows in several tables, and the filter itself is working fine. But, outside of the tables, I need to get the number of results (if filtering isn't happening, get the total) as well as number of parents included. I'm currently using:
<tr ng-repeat="child in (filteredChildren = (parent.children| filter: query))">
I can get that outside of the children repeat in the parent repeat. But, I also need a grandparent repeat outside of all of that where it will be referenced.
Here is a plunkr illustrating my problem.
There you can see filteredChildren returns nothing when in the grandparent's repeat, but it does when in the parent's repeat.
Is it possible to access the filter's results outside of nested ng-repeats?
It's possible, but the key to understanding why lies in understanding in what scope each filteredChildren
variable lives.
filteredChildren
is a filtered version of parent.children
and lives in the same scope. In fact, it is declared in that scope - that is the scope inside (i.e. for each iteration of) the "parent" ng-repeat
. So, in other words, it is defined in the child scope of the "grandparent" ng-repeat
.
Instead of creating a new variable for a filtered array, create it as an item of the array (with corresponding index of each parent) defined at the grandparent level. Let's say, it will be defined on each grandparent
variable:
<div ng-repeat="grandparent in grandparents">
<div ng-repeat="parent in grandparent.parents" ng-init="pIdx = $index">
<div ng-repeat="child in (grandparent.filteredChildren[pIdx] = (parent.children| filter: query))">
</div>
</div>
</div>
Of course, this will create an array of arrays and you would need another function to calculate the total number of children for a grandparent:
$scope.sumLength = function(arrayOfArrays){
var sum = 0;
for (var i = 0; i < arrayOfArrays.length; i++){
var childArray = arrayOfArrays[i];
if (childArray) sum += childArray.length;
}
return sum;
}
You could then add it inside "grandparents" ng-repeat
:
<div ng-repeat="grandparent in grandparents"
ng-init="grandparent.filteredChildren = []">
total children: {{sumLength(grandparent.filteredChildren)}}
...
</div>