How to access a custom filter in ng-repeat using AngularJS

I'm working on creating a filter to sort through the items displayed in a table. Specifically, I want to filter out items based on a certain property value that may change depending on user input. I have attempted the following approach and it seems to be functioning correctly. For example, I am looking to display all cities in my array of countries that are not named Stockholm or Gothenburg.

<table>
    <tr ng-repeat="city in cities | filter: name:'!'+'Stockholm' || 'Gothenburg'">
        <td>...</td>
        <td>...</td>
        <td>...</td>
    </tr>
</table>

However, I would like to achieve this programmatically by using a function to generate the filter, but I am facing difficulties in making it work.

<table>
    <tr ng-repeat="city in cities | filter: getFilter()">
        <td>...</td>
        <td>...</td>
        <td>...</td>
    </tr>
</table>

$scope.getFilter = function () {
    var filter = {};

    if (something) {
        filter['name'] = '!' + 'Stockholm';
    }

    if (somethingElse) {
        filter['name'] += ' ||' + 'Gothenburg';
    }

    return filter;
}

Answer №1

When using the filter method, each element is passed through for comparison against a specific condition.

$scope.do_not_display_these_cities = ['Stockholm', 'Gothenburg'];

$scope.applyFilter = function (element) {
    return $scope.do_not_display_these_cities.indexOf(element.name) < 0;
}

Any changes made to the list of cities will be reflected in the filtering process.

Answer №2

In my previous response, I suggested utilizing a Custom Filter provided by AngularJS:

Here is a simple example that demonstrates extracting the first letter of each word, converting it to uppercase, and then filtering the content.

<!DOCTYPE html>

<html ng-app="HelloApp">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<title></title>
</head>
<body ng-controller="HelloCtrl">
<form>
  <input type="text" ng-model="name"/>
</form>
<div>{{name|titlecase}}</div>
<script type="text/javascript">
    // Defining a custom module with a filter
    angular.module('CustomFilterModule', [])
        .filter( 'titlecase', function() {
            return function( input ) {
                return input.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
            }
        });
    // Angular App setup 
    angular.module('HelloApp', [ 'CustomFilterModule'])
        .controller('HelloCtrl', ['$scope', function($scope){
            $scope.name = '';
        }])
</script>
</body>
</html>

For a live demonstration, you can visit this link:

http://plnkr.co/edit/Ys4pgmKVRcSRFeg8unWr?p=preview

Please note: This example serves as a guideline for using AngularJS custom filters. It may require modifications to suit your specific needs.

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

Having trouble uploading files with jQuery File Upload functionality

Issue: I need to set a session variable and redirect the user to a different PHP page after uploading a .txt file using jQuery File Upload. HTML code (upload.php): <!-- The fileinput-button span is used to style the file input field as button --> ...

Inserting items into an array entity

I am attempting to insert objects into an existing array only if a certain condition is met. Let me share the code snippet with you: RequestObj = [{ "parent1": { "ob1": value, "ob2": { "key1": value, "key2": va ...

Tips for creating a scrollable smiley input field

I have a chat system where I am incorporating smileys from a predefined list. QUERY I am looking to create a scrolling feature for the smileys similar to how it is implemented on this particular website. The twist I want to add is to have this functiona ...

Perform an action when the timer reaches zero

I am working with a database entry that contains the following information: { _id:"fdjshbjds564564sfsdf", shipmentCreationTime:"12:17 AM" shipmentExpiryTime:"12:32 AM" } My goal is to create a timer in the front end ...

What method is most effective for combining two JSON files in Angular?

My data includes a json file with a product list that looks like this: [{"id":76, "name":"A", "description":"abc", "price":199, "imageUrl":"image.jpg", "productCategory":[{ "categoryId":5, "category":null },{ "categoryId":6, " ...

Organizing MVC5 with Angular JS: How to Create an Effective Folder Structure

As someone new to Angular and eager to learn best practices, I'm wondering about the ideal folder structure for an ASP.NET MVC5 AngularJS application. MVC5 default layout - Controllers Folder - Models Folder - Views Folder ---> Action Name Folder ...

What are some strategies for improving the speed and efficiency of traversing an XML file with AJAX?

I am currently working with an XML file structured like this: <UUT> <DKBFile>091750</DKBFile> <part> <name>FL_U1</name> <xcoord>439</xcoord> <ycoord>132</ycoord> <width>55</width ...

Update image source dynamically using AJAX and jQuery

Within my app, there exists a web page that contains numerous images with dynamically generated source URLs obtained by sending get requests to the rails server. Initially, these images are assigned a default source. Upon loading the page, another request ...

What is the best way to find out if an array index is within a certain distance of another index?

I'm currently developing a circular carousel feature. With an array of n items, where n is greater than 6 in my current scenario, I need to identify all items within the array that are either less than or equal to 3 positions away from a specific inde ...

Unable to retrieve custom CSS and JS files hosted on the server

Encountering Server Issue My server is returning a 404 NOT FOUND error when trying to access my static files: css and js. In IntelliJ IDEA, the path appears correct as shown in the image https://i.stack.imgur.com/nTFv9.png. However, upon accessing the pa ...

Unable to view any output in the console while attempting to troubleshoot a login functionality

My current setup involves using Node.js with Express and Pug templates. I have encountered an issue with a login function that is not functioning as expected. In order to troubleshoot the problem, I attempted to log the credentials (email and password) to ...

Using JQuery to implement a date and time picker requires setting the default time based on the server's PHP settings

I have implemented a jQuery UI datetime picker in my project. As JavaScript runs on the client side, it collects date and time information from the user's machine. Below is the code snippet I am currently using: <script> // Function to set ...

What about nested elements with percentages, set positions, and fixed placements?

Picture: I am working on a design with a yellow container div that I want to keep at 50% width of the window. Inside this container is a purple image div that stretches to 100% of the parent container's width, and there is a pink sticky label positi ...

Ways to remove a JSON item based on its index position?

In my JSON object, I am trying to find a way to remove the first element. Here is an example of what I have: var obj1 = {property:'something', does:'somethingElse', is:'somethingCool'}; var obj2 = {does:'somethingElse&ap ...

What do I need to verify? An uncaught TypeError has occurred in the promise, indicating that the property 'MyFunctionName' cannot be read from an undefined URL

The issue arises solely in the compiled application, leading me to believe it's a browser-specific problem. However, I'm uncertain: I've inserted the following script into a webpage: async function exportChatAsXMLHelper(params){ let dis ...

Incorporate SVG files into a TypeScript React application using Webpack

I am trying to incorporate an SVG image into a small React application built with TypeScript and bundled using Webpack. However, I am encountering an issue where the image is not displaying properly (only showing the browser's default image for when n ...

Guide to integrating external plugins in an Angular application

Currently in the process of converting my project from jQuery to Angular. Wondering the best approach for utilizing plugins: 1. Is it advisable to swap out old jQuery plugins with Angular-specific ones? 2. Or would it be better to integrate them using co ...

I attempted various methods but was unable to successfully call the webmethod in the code behind using jQuery Ajax and Knockout

I have attempted various solutions, such as enabling friendly URL resolution and utilizing web method with session enabled, but unfortunately, the issue remains unresolved. I kindly request your assistance in resolving this matter. Here is my HTML code for ...

Simulating an API request using Vue and Jest/Vue test utils

Utilizing Vue for the frontend and Python/Django for the backend, I aim to create tests that verify the functionality of my API calls. However, I am encountering difficulties when attempting to mock out the Axios calls. I suspect there might be an issue w ...

Ways to extract data from an array nested within a JSON object

I am seeking guidance on how to access the value of "result 2" from my JSON object using jQuery or pure JavaScript. var jsonarray = [{ title: "Category1", items: [{ result: "Item1", //Nested array items2: [{ //How to get the value o ...