You can add condition to ng-repeat using filter option in angularjs.
If you have a data with multiple records and want to separate it using condition in ng-repeat, use filter option in angularjs. In below example I have explained, how you can use filter to display a set of record conditionally.
Below is the JSON data which will be used to display records using different conditions.
$scope.SampleJSONList = [
{ "Name": "Rahul", "Age": 20, "IsActive":true },
{ "Name": "Dee John", "Age": 16, "IsActive": true },
{ "Name": "Shaila", "Age": 24, "IsActive": false },
{ "Name": "XYZ", "Age": 30, "IsActive": true },
{ "Name": "Tom", "Age": 40, "IsActive": true },
{ "Name": "Pranay", "Age": 23, "IsActive": false },
{ "Name": "Rahul", "Age": 20, "IsActive": false }
];
You can add condition on attribute inside filter enclosed in curly braces. But it only match the content on the basis of your search.
ng-repeat="item in List | filter: {condition}"
I am adding condition on IsActive attribute IsActive = true. It will fetch all the record where column IsActive is true.
<div class="width50">
<table class="webGrid">
<tr>
<th>Name</th>
<th>Age</th>
<th>Is Active</th>
</tr>
<tr data-ng-repeat="item in SampleJSONList | filter: {IsActive: true}">
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
Here is the output.
If I change condition to fetch record where IsActive = false, it will fetch all the records where column values are set to false.
<div class="width50">
<table class="webGrid">
<tr>
<th>Name</th>
<th>Age</th>
<th>Is Active</th>
</tr>
<tr data-ng-repeat="item in SampleJSONList" ng-if="item.Age >20 && item.IsActive === true">
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
Output:
You can add condition using ng-if also and this is effective too. You can apply any condition to your list using ng-if attribute. In below example, I have put condition where Age > 20 and IsActive is true. ng-repeat will fetch all records which full fill this scenario.
<div class="width50">
<table class="webGrid">
<tr>
<th>Name</th>
<th>Age</th>
<th>Is Active</th>
</tr>
<tr data-ng-repeat="item in SampleJSONList" data-ng-if="item.Age > 20 && item.IsActive === true">
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
Output:
Hope this helps you. Please like, rate and share this article and please don't forget to write your comments/suggestions in comment section below. It helps us improving quality of article and motivate us to write more.