AngularJS - Filter out items from ng-repeat that match specific string criteria

After successfully cleaning up an external JSON URL feed by removing unnecessary special characters through a filter in my AngularJS code, I am now faced with the challenge of filtering out specific items from an ng-repeat based on a certain string.

angularJS.filter('removeChar', function(){
    return function(text) {
        text = text.replace(/\[[^\]]+\]/g, ''); // Characters inside Brackets
        return text.replace(/\;.*/, ''); // Characters after Colon
    };
});

<span ng-bind-html-unsafe="item | removeChar">{{item}}</span>

For instance, I want to exclude items containing the words 'Red' or 'Green' from being displayed in the ng-repeat. Here is how I envision using the filter:

<div ng-repeat="item in items | removeItem">{{item['flowers']}}</div>

The following items are considered:

<div>Blue Roses</div>
<div>Red Roses</div>
<div>Orand and Green Roses</div>
<div>Yellow Roses</div>
<div>Red and Green Roses</div>

With the filter applied, only these items will be displayed:

<div>Blue Roses</div>
<div>Yellow Roses</div>

I would appreciate it greatly if someone could provide me with a helpful example.

Thank you! Roc.

Answer №1

If you want to exclude specific strings from your search, you can utilize the filter function with the ! predicate:

div ng-repeat="item in items | filter:'!Red' | filter: '!Green'">{{item['flowers']}}</div>

By using filter:'!Red', any item containing "Red" will be filtered out. The remaining results are then passed through filter: '!Green', removing any items with "Green."

For more information, refer to the AngularJS documentation: http://docs.angularjs.org/api/ng.filter:filter

Performance Update

To investigate filtering costs, a performance test was conducted on my system with 1,000 strings (items). Here are the results of 4 tests:

1) Showing all 1000 using DI 281,599 ops/sec

  {{items}}

2) Displaying all 1000 using ng-repeat (no-filter): 209,946 ops/sec 16% slower

  <div ng-repeat="item in items"> {{item}}</div>

3) ng-repeat with one filter 165,280 ops/sec 34% slower

  <div ng-repeat="item in items | filter:filterString1"> {{item}}</div>

4) ng-repeat with two filters 165,553, ops/sec 38% slower

  <div ng-repeat="item in items | filter:filterString1 | filter:filterString2"> {{item}}</div>

Although this test is not fully controlled and may be influenced by factors like caching, it provides interesting insights into relative performance levels.

Answer №2

When using the filter function, you have the ability to utilize any function that is accessible within the current scope as an argument. This allows for greater flexibility in how you manipulate data, as demonstrated below.

Example of implementing this concept:

<div ng-app="" ng-controller="FooCtrl">
    <ul>
        <li ng-repeat="item in items | filter:myFilter">
            {{item}}
        </li>
    </ul>
</div>

In the JavaScript code:

function FooCtrl($scope) {
    $scope.items = ["foo bar", "baz tux", "hoge hoge"];

    $scope.myFilter = function(text) {
        var wordsToFilter = ["foo", "hoge"];
        for (var i = 0; i < wordsToFilter.length; i++) {
            if (text.indexOf(wordsToFilter[i]) !== -1) {
                return false;
            }
        }
        return true;
    };
}

To see the implementation in action, visit this live example on Fiddle. http://jsfiddle.net/2tpb3/

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

Waiting for the listener script to finish its task in an Ajax call and then informing the user

I have developed a unique program that allows users to submit test cases from a specific webpage (main.php). The webpage triggers an ajax request to insert user data into MySQL using the file insert.php, with the value done=0. Subsequently, there is a list ...

Avoiding caching of GET requests in Angular 2 for Internet Explorer 11

My rest endpoint successfully returns a list when calling GET, and I can also use POST to add new items or DELETE to remove them. This functionality is working perfectly in Firefox and Chrome, with the additional note that POST and DELETE also work in IE ...

Inspect all checkboxes created by JavaScript

I'm attempting to develop a checkall checkbox that will automatically select all the checkboxes I've created using JavaScript. Firstly, I gather the number of rows and columns from the user and then use JavaScript to generate a table and insert ...

Convert XML to an HTML table in real-time as new elements are introduced

Currently, I have JSON and AJAX code that fetches XML data every second, which is working smoothly. When I added an XML element, it automatically gets added to an HTML table. The issue arises when I call the function every 3 seconds; the page refreshes due ...

premature submission alert on button press

I'm encountering an issue where my form is being submitted prematurely when I click on the button. The desired behavior is for the button to create a textarea upon clicking, allowing me to write in it before submitting by clicking the button again. Ho ...

I require assistance in implementing a button for executing this specific HTML code

Can someone assist me in embedding my HTML code into a button so that when the button is clicked, my code executes? function loadProgressBar() { var bar = document.getElementById('progressBar'); var status = document.getElementById(&ap ...

The generation of the page fails due to the absence of defined data

Every time I try to start my server, the error message pops up saying 'data is not defined', even though I have already defined the data content. export default class App extends Component { data = [ { key: "john", val ...

Showing text above bars in MUI X BarChart

I am currently utilizing the <BarChart> component from @mui/x-charts (version "^6.19.1") and I am looking to enhance readability by displaying the data values on top of each bar. Current Output: view image description here Desired Outc ...

Displaying PHP content using JavaScript classes

I have a popup feature implemented in JavaScript and all the necessary scripts added to my HTML page. I am attempting to load a PHP page in the popup when the submit button of my form is clicked. The popup is functioning correctly for buttons like the one ...

Protected Bootstrap Environment

Bootstrap is an amazing tool, but it tends to enforce too many opinions. The selectors used in its rules are quite broad, such as input or label. Is there a method to isolate Bootstrap's CSS so that it only impacts elements within a container with a ...

Steering clear of using relative paths for requiring modules in Node.js

When it comes to importing dependencies, I like to avoid using excessive relative filesystem navigation such as ../../../foo/bar. In my experience with front-end development, I have found that using RequireJS allows me to set a default base path for "abso ...

Employing the validateAll() function in conjunction with a personalized v-select component within the scope

One of my recent scenarios involves scoping a form in order to validate it using the Vee-Validate method shown below. validateTRForm: function (scope) { this.$validator.validateAll(scope).then((result) => { if (result) { } ...

Executing SQL queries in JavaScript using PHP functions

Is it allowed, or is it a good practice? It worked for me, but what issues might I face in the future? Just to clarify, I am new to PHP scripting. // button <button type="button" class="btn btn-primary" id="Submit-button" >Save changes</button> ...

The impact of Ajax on jQuery document loading within an Ajax form

I'm currently using jQuery to change the colors of cancelled bookings in a Drupal view, and it's working well. jQuery(document).ready(function(){ jQuery(".bookingstatus:contains('Cancelled')").css("color","red"); }); However, when ...

I can't seem to figure out why this isn't functioning properly

Upon examining the script, you'll notice the interval() function at the very bottom. The issue arises from bc-(AEfficiency*100)/5; monz+((AEfficiency*100)/5)((AFluencyAProduct)/100); For some reason, "bc" and "monz" remain unchanged. Why is that so? T ...

Implement a function in JavaScript to sum quantities for identical JSON objects

I am looking to calculate the total quantity for each category. var items = [ { cat: 'EK-1',name:"test",info:"mat", quantity: 3}, { cat: 'EK-2', name:"test2",info:"na ...

Errors are encountered when attempting to use `usePathname()` and `useRouter()` functions. `usePathname()` returns null while `useRouter()` causes errors stating "NextRouter not mounted" and "invariant

I'm encountering an issue with implementing active navlinks in NextJS version 13.4.4. I need to access the current URL for this solution, but every attempt ends up failing. My folder structure is organized as follows: .next components Header header ...

Experiencing an "ENOTFOUND" error after attempting to make a large volume of API calls, possibly in the range of 100,000, to maps.google

I have a requirement to send a large number of requests to https://maps.googleapis.com/maps/api/place/queryautocomplete/json. Currently, I am fetching lists of strings from multiple files and sending requests to the mentioned API. When I test with 100 str ...

Unraveling the Mystery of React Event Bubbling: Locating the Desired

I am working with a <ul> Component that wraps several <li> Components. To streamline my code, I would like to avoid adding an individual onClick handler to each li and instead utilize a single handler on the parent ul element to capture the bub ...

Having trouble capturing the CHANNEL_ANSWER event in my node.js script when communicating with Freeswitch

Greetings to all! I have a query regarding freeswitch. Although my experience with freeswitch is limited, I am currently working on connecting my node js script to the freeswitch server. So far, I have managed to establish a successful connection and gene ...