Jesús Otero Jesús Otero - 1 month ago 25
AngularJS Question

ng-table filtering of concatenated values from scope

I created an application in AngularJs with ngTable, I'm using ngTable to display the user data and by requirements, I must use a single column in a table to filter by first and last name, which are separated in the

$scope
and I concatenate the result on the table cell. But I cannot filter by the concatenation.

I've tried to create a custom filter as it's outlined on http://bazalt-cms.com/ng-table/example/11 to accomplish this task, unsuccessfully so far.

I could modify the scope when the data is received, by looping through the array, but the result set is expected to be pretty large and I don't think that'd be the correct way to do it.

Below is a simplified example. Is there an 'Angular Way' to filter by the concatenated string, using a model or a filter?.

Can anyone give me advice or point me in the right direction?

Many thanks in advance.



var app = angular.module('app', ['ngTable']);

app.controller('IndexCtrl', function ($scope, $filter, ngTableParams) {
$scope.people = [{
"id": 1,
"firstName": "Chuck",
"lastName": "Norris",
}, {
"id": 2,
"firstName": "John",
"lastName": "Lennon",
}, {
"id": 3,
"firstName": "Bender",
"lastName": "Rodriguez",
}];
$scope.peopleCopy = $scope.people;
$scope.mytable = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
name: 'desc'
}

}, {
getData: function ($defer, params) {
$scope.people = angular.copy($scope.peopleCopy);
var filteredData = $filter('filter')($scope.people, params.filter());
$scope.people = $filter('orderBy')(filteredData, params.orderBy());
$defer.resolve($scope.people);
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="http://bazalt-cms.com/assets/ng-table/0.3.0/ng-table.js"></script>
<body ng-app="app">
<div ng-controller="IndexCtrl">
<table border="1" ng-table="mytable" show-filter="true">
<tr ng-repeat="person in $data">
<td sortable="id" data-title="'Id'">{{person.id}}</td>

<!--td I want to sort by firstName + lastName -->
<td sortable="firstName" filter="{ 'firstName': 'text' }" data-title="'Name'">{{person.firstName +' '+ person.lastName}}</td>
</tr>
</table>
</div>
</body>




Answer

Utimately, I solved the filtering by using a simple filter (shown below). that adds the value person.fullName to the current object collection used in ng-repeat by the table

 $scope.getFullName = function(person) {
     return person.fullName = person.name + ' ' + person.lastName;
 }

and referencing it in the ngTable's ng-repeat

<tr ng-repeat="person in $data | filter:getFullName">

Then using the newly added value to the object with {{person.fullName}} in where needed (in the filter and cell value).

<td data-title="'Name'" sortable="'person.fullName'" 
    filter="{ 'fullName': 'text' }" header-class="ngtable-header"
    class="ngtable-td">{{ person.fullName }}</td>