1future 1future - 1 year ago 66
AngularJS Question

How to filter an Array by Name in AngularJS

In my project I have a table in which I'm looping through an array. I want the user to have options of filtering the table by either showing their data against their name or show all the data.

I have a controller like this:

var app = angular.module('app', []);
app.controller('Ctrl',[], function($scope){
$scope.LoggedInTeacher = 'Papa Johns';
$scope.Teachers = [{Id: 1, Name: 'Patricia Johns' , Subject: 'Science'},
{Id: 2, Name: 'Veronica Smith' , Subject: 'Maths'},
{Id: 3, Name: 'Clifford Harris' , Subject: 'Music'},
{Id: 4, Name: 'Papa Johns' , Subject: 'Catering'},
{Id: 5, Name: 'Bill Gates' , Subject: 'Information Tech'},
{Id: 6, Name: 'Papa Johns' , Subject: 'Dance'}



//Here is my View - filtering my array

<div ng-controller = "Ctrl">


<th> Name </th>
<th> Subject</th>


<tr ng-repeat=" t in Teachers">



The above context in working fine but i need to filter the results by the logged in user name. So for example below the table i want to have two check boxes to filter the data like so:

<input type="checkbox" ng=model="filter table by LoggedInTeacher "> Show only Mine
<input type="checkbox" ng-model="show all"> Show All

How would I go about in achieving this ?

Thank you

Answer Source

Save filter entered by user such as 'filterValue'. In each options, change value of filterValue when user select checkbox.

<input type="checkbox" ng-click="filterValue = LoggedInTeacher"> Show only Mine </input>
<input type="checkbox" ng-click="filterValue = ''"> Show All </input>

In the ng-repeat, change your expression:

<tr ng-repeat="t in Teachers | filter: filterValue">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download