I need to access data that was already filtered on a template (inside a ng-repeat) from my controller.
Here's what I mean:
I have this table in my template:
<table class="table">
<thead>
<th>Name</th>
<th>Gender</th>
</thead>
<tbody>
<tr ng-repeat="person in persons | filter:query">
<td>{{person.name}}</td>
<td>{{person.gender}}</td>
</tr>
</tbody>
</table>
Then I have a <select>
that is used to filter data by gender
<h1>Cluster:</h1>
<select ng-model="query.gender" >
<option value ="">ALL</option>
<option value ="male">Male</option>
<option value ="female">Female</option>
</select>
This works ok.
If someone selects one of the options, I need to do something with the filtered results. That's why I have a $watch in my controller that looks for changes to the filter query:
$scope.$watch('query.gender', function(newValue, oldValue) {
// Here is where I need to get filtered results
});
My question is:
How do I access the FILTERED content from the controller?
I'd like this preferably without having to do another "filtering" operation in the controller... (since the data was already filtered, the result is sitting somewhere in memory, right?)
You can simplify your code with the following:
<tbody>
<tr ng-repeat="person in (filteredPersons = (persons | filter:query))">
<td>{{person.name}}</td>
<td>{{person.gender}}</td>
</tr>
</tbody>
After that, you can get access to $scope.filteredPersons
into controller or {{filteredPersons}}
right into the view :)
I'm not entirely sure, but you can use the filter function in your controller. So try something like:
$scope.$watch('query.gender', function(newValue, oldValue) {
var x = $filter('filter')($scope.persons, $scope.query);
});
x should then contain the same filtered data as in your table I think. Have a look at the docs here: http://docs.angularjs.org/api/ng.filter:filter for some more info.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With