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

Personalized Dropdown Menus for Internet Explorer 8

Seeking recommendations for stylish custom select boxes that are compatible with IE8 and function flawlessly. Many of the custom scripts I've come across perform admirably, but tend to suffer setbacks when it comes to working smoothly in IE8. ...

While troubleshooting the app, I encountered an error that says: "The property 'answers' cannot be read as it is undefined."

Everything was going smoothly with my app until it suddenly crashed, displaying the error message "Cannot read property 'answers' of undefined". Let's take a look at the specific piece of code causing the issue: function mapStateToProps({ ...

Blend the power of Node's CommonJS with the versatility of Typescript's ES modules

I currently have a Node.js v10 legacy application that was built using CommonJS modules (require). The entire codebase is written in JavaScript. However, I am considering upgrading the app and refactoring a specific part of it to use TypeScript modules ( ...

Angular 2 doesn't reflect changes in component variables in the view until mouseover happens

Since updating from angular2-alpha to the latest version, I've noticed that when a boolean value changes in my *ngIf directive, it doesn't reflect in the view until certain actions are taken. Here is the specific component code: declare var CKE ...

Exclusion of specific numbers in the pattern

My task involves managing a list of exclusion numbers. For example, the following numbers are included in the exclusion list: (400276|400615|402914|404625) The pattern must prevent me from entering any of these numbers as the first 6 digits in the input ...

AngularJS login form with JSON data

I am currently learning Angular and focusing on the login form implementation. The specific model I am working with can be found in this PLNKR. There are two challenges that I am struggling to resolve. Issue 1: I'm trying to figure out how to tur ...

Firebase scheduled function continues to encounter a persistent issue with an "UNAUTHENTICATED" error being consistently thrown

I have created a firebase-function that is scheduled to retrieve data from an external API source and save it in Firestore. const functions = require("firebase-functions"); const admin = require("firebase-admin"); const { default: Axios ...

Sharing the directive scope with transcluded elements is crucial for enabling seamless communication

I've been working on a reusable modal directive, but I'm facing an issue with the transcluded elements creating their own scope. You can see the problem in action on this JSFIDDLE. Here is how it currently functions. <button ng-click="show=!s ...

The JSON data structure is not being maintained

I am facing an issue with updating the json object model values using the code below. Even after changing the values, it seems like the model is not getting updated. I tried removing the async code and that worked. Why does the async code not work in this ...

What are some secure methods for integrating iframes into an Angular 7 project?

Is there a secure method to set the URL for an iframe without bypassing security measures like using this.domsanitizer.bypassSecurityTrustResourceUrl(url)? While this approach may be flagged as a high vulnerability by tools such as Veracode, is there a w ...

Angular UI Router provides a convenient way to set up nested states for the home page, allowing for a clear distinction

Embarking on a new project using the MEAN boilerplate provided by MEAN.JS (not .IO). I'm fresh to ui-router and facing difficulty in achieving this particular scenario: If the user is logged in, direct them to state "home.loggedIn". If the user is ...

Testing Restful API Endpoints and Code Coverage with Node.js using Mocha

My time in Istanbul has been delightful, and I've been dabbling in different Node.js coverage libraries. However, I'm facing a challenge. Most of my unit tests involve making HTTP calls to my API, like this: it('should update the custom ...

How to eliminate the unnecessary gap between rows in a Vue div displayed as a grid

I have recently started working with Vue and in my current project, I encountered a challenge where I needed to display 2 players in each row within a div. To achieve this, I utilized the display: grid; CSS property on the playerDiv id. However, I am facin ...

Tips for avoiding accidental unit conversion in jQuery

Imagine having the following code: var $element = $('<div/>'); $element.css("margin-left", "2cm"); console.log($element.css("margin-left")); When tested in Chrome, it doesn't return anything, but Firefox shows "75.5833px". Any sugges ...

Encountering an Issue with Installing angular-cli via npm

Currently, I am in the process of installing angular-cli using npm. Nodejs and git are both up-to-date on my system. I have confirmed that I am not connected to a proxy server by checking both through netsh winhttp show proxy and Internet Explorer LAN sett ...

What is the best way to utilize $(target) within a directive?

I created a custom directive for selecting time using two blocks. The challenge is detecting the target event on specific blocks within the directive's template. Directive Template: <div class='time-picker-container'> <div clas ...

Click on a div in AngularJS to be directed to a specific URL

I'm currently working on developing an Angular mobile app and I want to be able to navigate to a specific URL, like www.google.com, when a particular div is clicked. Unfortunately, I'm still new to the world of Angular and struggling to achieve t ...

After an ajax call in ASP .NET MVC3 using Razor, jQuery may not function properly

When I perform a post back to obtain a partial view using ajax, I utilize the following code to render the partial view within a div named 'DivSearchGrid'. <script type ="text/javascript" > $('#Retrieve').click(function ( ...

Using Vue's computed property setter with an object as a prop

I have a new concept for an input component where different objects can be passed, displayed as CSV, and allow for text editing/validation with style changes based on validation results. Check out the code snippet I've been working on: <div id=&quo ...

What is the best way to remove text from a box when a user clicks on it?

After successfully placing G in the selected box upon clicking it, I now want to work on removing it when clicked again. I'm encountering an issue with my current code - can anyone help me identify what's wrong and suggest a solution? Below is ...