The performance of AngularJS Filter leaves much to be desired

In my project, I am working with an array ($scope.names) that contains simple objects. I have implemented functions to clean the values from diacritics and when I console.log the result, it appears correct. For example, 'La 45 km nord- vest de Bucureşti' becomes 'La 45 km nord- vest de Bucuresti' after cleaning.

I have also applied the same method to another variable ($scope.searchText) to ensure that the searchable text is compatible. So far, everything seems to be working fine.

However, I am facing an issue where even though I have standardized the values of these two variables, the filtering process is not functioning properly. When I try to search for 'Bucures', it does not display the object that contains the cleaned word 'Bucures' (original word 'Bucureş')...

What could I possibly be doing wrong in this scenario?

The complete code can be found here: http://plnkr.co/edit/D5WfiOGd5I3QfcNVdOmr?p=preview

This is the angular script being used:


var app = angular.module('myApp', []);
app.controller('namesCtrl', function($scope, $filter) {
$scope.names = [
{
"adresa": "Str. Calafatului nr. 10",
"latitudine": "44.1",
"localitatea": "GALICEA MARE",
"longitudine": "23.3",
},
{
"adresa": "bd. Elisabeta nr. 1",
"latitudine": "44.170901",
"localitatea": "CONSTANŢA",
"longitudine": "28.663195",
},
{
"POTLOGI": "La 45 km nord- vest de Bucureşti",
"latitudine": "44.564319",
"localitatea": "POTLOGI",
"longitudine": "25.588091",
}
]

$scope.searchText = "";
$scope.searchCleanText = "";
$scope.myFilter = function (items) {
for (var i = 0; i < items.length; i++) {
var boolChk = false;
angular.forEach(items[i], function (value, key) {
var cleanValue = removeDiacritics(value).toLowerCase();
if (boolChk === false) {
boolChk = cleanValue.includes($scope.searchCleanText);
}
console.log(value + ' ' + cleanValue.includes($scope.searchCleanText) + '\tboolChk = ' + boolChk);
return boolChk;
});
}
}

$scope.$watch('searchText', function() {
$scope.searchCleanText = removeDiacritics($scope.searchText).toLowerCase();         
$scope.showItems = $filter('filter')($scope.names, $scope.searchText, $scope.myFilter($scope.names));
console.log($scope.showItems);
});
});

Answer №1

I’ve updated the filter code with some modifications.

$scope.updatedFilter = function (item) {
            var flag = false;
            angular.forEach(item, function (value, key) {
                var cleanValue = removeDiacritics(value).toLowerCase();
                if (flag === false) {
                    flag = cleanValue.includes($scope.searchCleanText);
                }
                console.log(value + ' ' + cleanValue.includes($scope.searchCleanText) + '\tflag = ' + flag);
                return flag;
            });
            return flag;
        }

    $scope.$watch('searchText', function() {
            $scope.searchCleanText = removeDiacritics($scope.searchText).toLowerCase();         
      $scope.displayItems = $filter('filter')($scope.names, $scope.searchText, function(actual,expected){return $scope.updatedFilter(actual);});
      console.log($scope.displayItems);
    });

Explore this Plunk

Answer №2

The function used 'function (actual, expected)' to determine a boolean result:

$scope.filterFunction = function (actual, expected) {
    if (typeof actual === 'object') {
        var obj = actual;
        
        var boolCheck = false;
        angular.forEach(obj, function (value, key) {
            var cleanedValue = sanitizeText(value).toLowerCase();
            if (boolCheck === false) {
                boolCheck = cleanedValue.includes($scope.searchQuery);
            }
        });
        console.log(obj);
        console.log(boolCheck);
        return boolCheck;
    }
}

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

What is the best way to showcase the content from multiple uploaded files?

Below is an example demonstrating how to display the contents of a single uploaded file. .js $scope.uploadFilename = function (files) { if (!files[0]) { return; } var reader = new FileReader(); reader ...

What could be causing the spotlight in my three.js scene to stay centered in the camera perspective, but only when using Chrome on an Android device?

Currently, I am experimenting with AngularJS and Three.js to create a small example of a VR application. To define controls based on whether the user is using a mobile device or not, I have implemented OrbitControls for non-mobile devices and DeviceOrienta ...

The MaterialTable component is indicating that there is no property called 'tableData' on the IPerson type

Incorporated an editable attribute to my MaterialTable component. Currently looking for a way to retrieve the index of updated or deleted items within the onRowUpdate and onRowDelete methods. To replicate the issue, refer to this minimal sandbox example: ...

Ways to detect if there is a new database record and display it in the notification bar with an alert

In the Django framework, I am retrieving data through an AJAX request from a database like this: $.ajax({ url: '/activity/', type: 'GET', data:{}, success: function(data) { // alert(data); var div1 = doc ...

Problem with reordering rows in a PHP DataTable

While attempting to retrieve data from a database table and display it in a DataTable, I encountered the following error: DataTables warning: table id=example - Invalid JSON response. To learn more about this error, refer to http://datatables.net/tn/1 ...

Having trouble getting haxe-pixi.js to function properly as it only shows a blank white screen

***UPDATE: Success! Managed to solve the issue. It turns out the missing library in the html file was causing the problem. The pixi.min.js file was not present in the haxelib directory, which seems a bit unusual. Here's a more challenging question: i ...

Starting a tab just once

I have successfully created 4 static HTML pages that include: Home About Services Contact Each page contains a link that leads to another static page named myVideo.html, which plays a video about me in a new tab. The link is available on every page so ...

Adjust grading system based on user interaction with JavaScript

I am currently working on a grading system for a website and I am attempting to modify the interpretation of grades when a column is clicked. Specifically, I am looking to convert Average (%) to Letters to 4.0 Grade Average. To achieve this, I am using Jqu ...

Using the class method to handle jQuery events alters the context

Is it possible to access the class context from within a method being used as a jQuery event handler? The example below illustrates the scenario: class EventHandler { constructor() { this.msg = 'I am the event handler'; } ...

Create a new division directly underneath the bootstrap column

Imagine having a bootstrap table like this: https://i.sstatic.net/kXHiP.jpg Now, if you want to click on a column and open a div with more details below it, is it achievable with CSS or JavaScript? https://i.sstatic.net/HIfkK.jpg I tried using the Metr ...

A guide on assigning a state variable to a dynamically generated component within a React application

I need to display user data from an array and have a button for each watchlist that deletes it. Although the backend is set up with a function deleteWatchlist, I am facing an issue in setting the state of the watchlistName for each watchlist after mapping ...

Tips for configuring ejs data within the data attribute and processing it using client-side JavaScript

My aim is to transfer leaderboard information from the server to the client-side JavaScript. This is the code on my server side: const leaderboard = [[dog,cat],[car,bus],[foo,bar]] const toJson = JSON.stringify(leaderboard) res.render('gam ...

Create a "predecessor" function to execute prior to all components

I'm struggling to find the right approach, but I want to ensure that all components in my app have access to the same data. Here is an overview of my current app structure: BeforeAngular.js function DataModel(json){ this.name = json.name || "No ...

Having trouble retrieving the full HTML code with the execute_script function in Python while web scraping

Currently, I am in need of HTML code to perform web scraping using Python. The particular website I am working with is that of a real estate agency. Prior to executing the onclick event for a button that changes pages, it is crucial for me to first obtain ...

Issue: Images are not displaying in jQuery slideshow.Possible cause: There

I'm currently working on developing a slideshow using jQuery and HTML. However, I've encountered an issue where only one image is displaying while the other slides are not showing up at all. I've been troubleshooting this problem but haven&a ...

Retrieving JSON information using Angular from JSONPlaceholder

Obtaining the JSON data from http://jsonplaceholder.typicode.com/ using Angular seems quite simple, yet I am struggling to find the right method. Can anyone provide guidance on how to achieve this? I have already attempted multiple approaches with no suc ...

Ensure that the input field requires the first letter to be capitalized and the subsequent letters to be in lowercase

There are numerous ways to capitalize the first letter and make the rest lowercase on Stack Overflow. However, I am looking for a method that can instantly enforce this rule in the input field. Being new to AngularJS, I am currently working with version 1 ...

Ways to incorporate javascript in ejs for verifying the existence of a value in an array

I have a products document containing an array of objects with user IDs. When rendering a page, I need to check if the logged-in user's ID is in that array. If it is, I want to display something different compared to users whose ID is not in the array ...

Exploring the assortment of reactions post-awaitReaction in node.js

The current code runs smoothly, but I encounter an issue when attempting to send messages after selecting either the X or check option. Instead of the expected outcome, I receive Despite my understanding that this collection is a map, all attempts to acce ...

Learn how to remove data from a React JS application without causing a page refresh by utilizing the useLoaderData() function in conjunction with React Router

I am working on preventing my table from refreshing with the new version of userLoadData from react-router-dom@6 after deleting some data. In an attempt to achieve this, I created a function called products() within useLoaderData. While this function succ ...