Matt Knight Matt Knight - 3 months ago 15
AngularJS Question

Angular filter results when user clicks on repeat

I am trying to create an Angular filter that allows users to click on a record and have the filter then show only that one record within the same repeater.

For example, when a person searches for last name "knight," they see some results. Then, when the user clicks on the specific record they want, they should see only that one record displaying in the repeater.

enter image description here
My html is this:

<md-list-item class="md-3-line" ng-repeat="value in ctrl.results" ng-click="ctrl.showRecord(value)">
<div class="md-list-item-text" layout="column">
<h4>Employee Id: <b>{{ value.employeeId }}</b></h4>
<h4>NetId: <b>{{ value.netId }}</b></h4>
<p>Name: {{ value.preferredFirstName }} {{ value.preferredLastName }}</p>
</div>
</md-list-item>


and it passes the selected record to my controller in this function:

vm.showRecord = function (selectedRecord, ev) {
//need my filter here
};


I have looked over a number of the examples on filters, but I don't quite see how to make the filter update the very same repeat that the user clicked on.




** Edit to show answer based on Tom Chen's work **

For anyone doing this with controller as syntax, here is the answer.
html:

<md-list-item class="md-3-line" ng-repeat="value in ctrl.results | filter:ctrl.selectedId" ng-click="ctrl.showRecord(value.employeeId)">
<div class="md-list-item-text" layout="column">
<h4>Employee Id: <b>{{ value.employeeId }}</b></h4>
<h4>NetId: <b>{{ value.netId }}</b></h4>
<p>Name: {{ value.preferredFirstName }} {{ value.preferredLastName }}</p>
</div>
</md-list-item>


controller:

vm.showRecord = function (selectedRecord) {
vm.selectedId = selectedRecord;
};

Answer

You can achieve this simply by using angular filter expression like this:

<md-list-item class="md-3-line" ng-repeat="value in ctrl.results | filter:vm.selectedId" ng-click="ctrl.showRecord(value.employeeId)">
    <div class="md-list-item-text" layout="column">
        <h4>Employee Id: <b>{{ value.employeeId }}</b></h4>
        <h4>NetId: <b>{{ value.netId }}</b></h4>
        <p>Name: {{ value.preferredFirstName }} {{ value.preferredLastName }}</p>
    </div>
</md-list-item>

and in your controller :

vm.showRecord = function (id) {            
    vm.selectedId = id;
};

UPDATED ANSWER WITH WORKING EXAMPLE

Here is an example in Plunker

Comments