Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular js: Access data filtered in ng-repeat (ngRepeat) from controller

Tags:

angularjs

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?)

like image 704
Nahn Avatar asked Feb 01 '14 14:02

Nahn


Video Answer


2 Answers

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 :)

like image 63
Artyom Pranovich Avatar answered Oct 16 '22 20:10

Artyom Pranovich


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.

like image 38
mylescc Avatar answered Oct 16 '22 21:10

mylescc