Ray Ray - 1 year ago 152
AngularJS Question

Angularjs ng-repeat with filter scope object

I have a requirement to filter rows in

based on whats in
. I have a data in
that contains all the customer information, but when looping through each customer, I would only like to show results based on whats in
. For example, only show rows of customers that have jobs that are in

Here is the JSFiddle link.

Here is what I have so far:


<table ng-app="app" ng-controller="AppsCtrl">
<tbody ng-repeat="customer in customerData">
<td><a href="#" class="main" ng-click="expandTable($event)">+</a></td>
<tr class="showhide">
<td> </td>
<td>Job title</td>
<tr class="showhide">


// AngularJS toggle table

var app = angular.module('app', []);
app.controller('AppsCtrl', function($scope) {
$scope.expandTable = function() {
// console.log($(event.currentTarget).parent().parent());
var data = [{
"name": "John",
"email": "JSmith@yahoo.com",
"DOB": "01/05/1968",
"Degree": " BSC",
"Job": "Engineer",
"Hobby": "Football",
"Country": "US",
"City": "Houston"
}, {
"name": "Jessica",
"email": "Jess@yahoo.com",
"DOB": "03/05/1976",
"Degree": " Accounting",
"Job": "CPA",
"Hobby": "Video games",
"Country": "US",
"City": "Fredericks"
}, {
"name": "Andrew",
"email": "AJoan@yahoo.com",
"DOB": "06/12/1998",
"Degree": " PHD",
"Job": "Professor",
"Hobby": "Writing",
"Country": "US",
"City": "San Diago"
}, {
"name": "Rich",
"email": "Rschol@yahoo.com",
"DOB": "09/21/1988",
"Degree": " PHD",
"Job": "Technician",
"Hobby": "Writing",
"Country": "US",
"City": "San Diago"
$scope.customerData = data;
$scope.filterObject = [{
"Job": "CPA"
}, {
"Job": "Engineer"

Any suggestion and help is really appreciated. :)

Answer Source

$scope.customerData = data.filter(function(user){
    var found = false; 
    	if(filter.Job === user.Job)
      	found = true;
    return found;

Fiddle: https://jsfiddle.net/nandorpersanyi/yLsxqkx8/

Regarding Nedev's answer: DOM filters can have an impact on performance, presuming we are handling large datasets (eg $scope.customerData has thousands of customers). In this case you are better off filtering within the controller, unless you need user interaction with the filter. And if your filter object updates dynamically, just $watch it for changes, then rerender customerData when changed

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download