Filtering concatenated values from scope in ng-table

I have developed an AngularJs application using ngTable to display user data. As per the requirements, I need to filter by a concatenated string of first and last name in a single column. Despite attempting to create a custom filter following the guidelines on , I have been unsuccessful so far.

While I could modify the scope upon receiving the data by iterating through the array, considering that the result set is expected to be large, it may not be the ideal approach.

Below is a simplified example. Is there a way in Angular to filter by the combined string using a model or a filter?

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 №1

To effectively filter by both fields, you can implement a custom filter function.

 $scope.people = [{
    "id": 1,
        "firstName": "Chuck",
        "lastName": "Norris",
}, {
    "id": 2,
        "firstName": "John",
        "lastName": "Lennon",
}, {
    "id": 3,
        "firstName": "Bender",
        "lastName": "Rodriguez",
}];

$scope.filterLastAndFirst= function(person, searchParam){
    return person.firstName.indexOf(searchParam) !== -1 || person.lastName.indexOf(searchParam) !== -1;
};

<li ng-repeat="item in products | filterLastAndFirst: searchParam">{{item.name}}</li>
// Remember to define $scope.searchParam

Alternatively, you can create a filter

app.filter('lastAndFirstFilter', function(){
    return function(objectArray, searchParam){
        var toReturn = [];
        angular.forEach(objectArray, function(value){
            if(value.lastName.indexOf(searchParam) !== -1 || value.firstName.indexOf(searchParam) !== -1)
                toReturn.push(value);
        });
        return toReturn;
    }
});

// Implementation:
var filtered = $filter('lastAndFirstFilter')($scope.people, searchTerm);

Answer №2

After much consideration, I was able to tackle the filtering issue by implementing a straightforward filter method (demonstrated below) that includes the value person.fullName in the current object collection used in ng-repeat by the table

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

and utilizing it in the ngTable's ng-repeat iteration

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

Subsequently, I employed the newly introduced value to the object with {{person.fullName}} wherever necessary (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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the wonders of array filtering and reducing in Javascript

Can someone help me turn an array of voter objects into a count of how many people voted? I'm just starting to learn JavaScript and feeling confused with the reduce and filter methods. When I run the code, I get undefined @@ function totalVotes(a ...

Reveal and Conceal, the ever-changing show

As I work on my blog, I want to make the layout more compact by having a link that reveals comments and entry forms when clicked. I've seen this feature on other sites as "Comments (5)", but I'm unsure how to implement it myself. Below is a snip ...

When using express, the response.sendFile() function is causing an Uncaught SyntaxError with the error message: Unexpected token <

Currently, I'm utilizing react-router with browserHistory. There is a specific function in my code that is meant to send the Index.html file since the routing is handled client-side with react-router. However, there seems to be an issue where the serv ...

"Exploring the Dynamic Routing Features of ASP.NET 5 in Combination with Angular

I'm currently working on a project using ASP.NET 5 in combination with AngularJS. Within my MVC application, I have two actions with corresponding views (Home and Web). Additionally, I have implemented four client-side routes using Angular. The challe ...

Generating a variety of modes from an array

My challenge is finding multiple modes from an array, but my code currently prints the modes multiple times. I specifically want to create an array with only 7 and 8 like this [7, 8] instead of [7, 7, 7, 7, 7, 8, 8, 8, 8, 8]. Can someone please assist me i ...

Pass data to three.js using an input form

I'm trying to figure out how to pass the value of an input form to a three.js workspace. Here's my code where I want to use a slider to change the radius of a sphere, without relying on the built-in controls of three.js since I'm new to HTML ...

PouchDB encountering issues with compatibility in Internet Explorer 8

While testing my PouchDB app on IE8, I encountered some errors. I have already included pouchdb.localstorage.js and es5.shim.js files in the index.html. Below are the errors that I came across: An error stating "Expected Identifier, string or number" fo ...

Error in Next.js PDFtron Webviewer: ReferenceError - 'window' is not defined

Currently, I'm faced with a challenge in setting up a PDF viewer on my nextjs static page. Having recently ventured into Next.js, I'm seeking assistance from you guys to resolve this issue or suggest an alternative approach. While trying to imple ...

Error: Attempting to access 'map' property of an undefined variable in NEXTJS

I've been struggling to retrieve an image from this API using getStaticProps, but for some reason I can't seem to make it work. In my code snippet, if I add a question mark like this, the console returns 'undefined'. What could be caus ...

Using specialized directives to communicate with an Api

I am having trouble accessing more than 10 objects from an API and the custom directive is not working as expected. Can anyone provide some suggestions or help? Below is the code snippet that I'm struggling with: mainView.html <div class="panel ...

Ways to extract information from a dynamically loaded webpage

Is there a way to extract data from a news website that automatically reloads at set time intervals? I want to use this data on my own website as information, whether it's in the form of images or text. Can anyone guide me on how to retrieve data from ...

Combining D3 and D3plus in an Angular web application: A complete guide

I'm currently integrating d3Plus sample code () into my angular-based webapp. This is the initial setup code: angular.module('UI', ['UI.controllers', 'UI.directives']); angular.module('d3Plus', ['d3' ...

Angularjs drop-down menu changes images with animation

<body ng-controller="myCtrl"> <input type="checkbox" ng-model="loaded"/> <select ng-model="list"> <option ng-repeat="option in data.availableOptions" value="{{option.name}}">{{option.id}}</option> </select> {{list}} &l ...

Using JavaScript and jQuery to toggle visibility of a dynamically created input field

This script dynamically generates a group of elements consisting of four input fields. Once an element is created, you can select or deselect it, which will trigger the corresponding editor to appear. I have implemented a function to specifically hide the ...

"Incorporating React with Redux using object-oriented programming principles

Coming from Angular, I was accustomed to having a separate class for each entity in my database, where all the entity's behavior was encapsulated. For example, a Users Class could look like this: export class User{ static notValid(u){ return ! ...

Issues with Bootstrap sidebar and footer functionality

I need to implement a consistent footer on multiple web pages created with jQuery and bootstrap 3. Following the example provided by Bootstrap, I have written the script below to add the footer: // Default $( document ).ready(function() { $(' ...

What is the best way to create a list with images in a dropdown menu using HTML?

Thanks so much for your assistance! Below is the code snippet I am currently working on <li><a href="#Language">*LanguageHERE*</a></li> I am hoping to turn this into a dropdown menu that displays flags representing all available ...

Is there a way to temporarily halt scrolling text and then resume?

Is there a way to pause the marquee for a few seconds at the end of each <li>, before continuing on to the next one? Here's my code: <div id="teks_container" > <marquee direction="up" scrollamount="3" height="200px"> <ul&g ...

Concealing certain columns when the table exceeds a certain size

Hello everyone, I am just starting out in the world of React and web applications. Please feel free to reach out if anything is unclear to you. Here is the table structure that I currently have: <div> <table id="mytableid" className=&qu ...

Adjusting the value of a user form with multidata in PHP and Javascript

I am looking for guidance on how to modify the value of an input in a form that contains multiple data entries. Here is my form: <form method="post" action="pax-flight.php#pax-flight" class="paxform"> <input type="hidden" value="{"data":{"us ...