1future
1future

Reputation: 255

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">

<table>

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

</tr>

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

<td>{{t.Name}}</td>
<td>{{t.Subject}}</td>
</tr>

</div>

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

Upvotes: 0

Views: 73

Answers (3)

Vu Quyet
Vu Quyet

Reputation: 1705

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">

Upvotes: 2

Niketan Raval
Niketan Raval

Reputation: 479

You can use this.

<tr ng-repeat=" t in Teachers | filter: {name: LoggedInTeacher}">

Upvotes: 0

Juan&#237;n
Juan&#237;n

Reputation: 851

You can use a filter like the following:

<tr ng-repeat=" t in Teachers | filter: {name: 'Bill Gates'}">

Instead of {name: 'Bill Gates'} you can put a variable defining the filter.

Upvotes: 0

Related Questions