Utilizing JavaScript filtering logic in Angular Filter with AngularJS

This inquiry originates from this source

Within the realm of Javascript, I have crafted a code to facilitate filtering, specifically showcasing elements from the array colors only if they correspond as values in cars.

var colors = ["blue","red","pink","yellow"];

var cars = [{"brand":"Ford","color":"blue"}
           ,{"brand":"Ferrari","color":"red"}
           ,{"brand":"Rolls","color":"blue"}];

var filteredColors = colors.filter(function(color) { 
    return cars.some(function(car) { 
        return car.color === color;
    }); 
});

console.log(filteredColors);

In an endeavor to apply this concept in Angular JS, I implemented the following:

$scope.colors =["blue","red","pink","yellow"];

$scope.cars=[ {"brand":"Ford","color":"blue"}
           ,{"brand":"Ferrari","color":"red"}
           ,{"brand":"Rolls","color":"blue"}];

$scope.filteredColors = function() {
    var colorsvar = $scope.colors;
    var carsvar = $scope.cars;
    return colorsvar.filter(function(color) { 
        return carsvar.some(function(car) { 
            return car.color === color;
        });
    });

};

Subsequently, within the view:

<ul>
    <li ng-repeat="n in colors | filter: filteredColors"> {{n}}
    </li>
</ul>

The anticipated outcome should be:

  • blue
  • red
  • However, the filtering process does not execute optimally. For further reference, please refer to the functional plunkr here. Any assistance provided will be greatly appreciated. Thank you!

    Answer №1

    If you're looking to create a custom filter, check out the example below:

    DEMO

    var app = angular.module("myApp",[]);
    app.controller("myCtrl",function($scope){
    $scope.colors =["blue","red","pink","yellow"];
    
    $scope.cars=[ {"brand":"Ford","color":"blue"}
               ,{"brand":"Ferrari","color":"red"}
               ,{"brand":"Rolls","color":"blue"}];
    
     
    })
    app.filter('myFilter', function() {
        // the filter takes an additional input filterIDs
        return function( filterColors, inputArray) {
            var filtered = [];
           angular.forEach(inputArray,function(key,value){
                 if(filterColors.includes(key.color) && !filtered.includes(key.color)) {
                    filtered.push(key.color);
                 }
           })
           return filtered;
        };
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    
    <div ng-app="myApp" ng-controller="myCtrl">
    <ul>
        <li ng-repeat="n in colors | myFilter: cars  track by $index"> {{n}}
        </li>
    </ul>
    </div>

    Answer №2

    Avoiding the need to use a filter, you can simply invoke the function within the ng-repeat directive.

    <li ng-repeat="n in filteredColors()"> {{n}}
     </li>
    

    Interactive Example:

    var app = angular.module("myApp",[]);
    app.controller("myCtrl",function($scope){
    $scope.colors =["blue","red","pink","yellow"];
    
    $scope.cars=[ {"brand":"Ford","color":"blue"}
               ,{"brand":"Ferrari","color":"red"}
               ,{"brand":"Rolls","color":"blue"}];
    
    $scope.filteredColors = function() {
        var colorsvar = $scope.colors;
        var carsvar = $scope.cars;
        return colorsvar.filter(function(color) { 
            return carsvar.some(function(car) { 
                return car.color === color;
            });
        });
    
    };
    })
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    
    <div ng-app="myApp" ng-controller="myCtrl">
    <ul>
        <li ng-repeat="n in filteredColors()"> {{n}}
        </li>
    </ul>
    </div>

    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

    sidebar that appears upon the initial page load

    I'm currently working on implementing a sidebar navigation panel for my website using JavaScript, HTML, and CSS. However, I am facing an issue where the sidebar automatically opens when the page is first loaded, even before clicking on the icon to ope ...

    Changing the value of an object property (illustrated using a basic linked list)

    I am working on a JavaScript Link List implementation as a beginner, and I have written the following code: var LinkList = function () { this.LinkedList = { "Head": {} }; }; LinkList.prototype = { insert: function (element) { var Node = this ...

    Is there a way to create a self-contained installation package for my Vue application?

    Is it possible for my application to be downloaded and installed without requiring internet access after the download is complete? I am looking to create a standalone installer for this purpose. Are there any suggestions on how to go about implementing t ...

    What is the best way to create an array within an object during the parsing process

    When working with a JSON object, I need to assign a value stored in the session against an ID. The JSON data is as follows: [ { "id": "a", "text": "a", "icon": true, "li_attr": { "id": "a" }, "a_attr": { "href": "#" ...

    What is the best way to update the style following the mapping of an array with JavaScript?

    I want to update the color of the element "tr.amount" to green if it is greater than 0. Although I attempted to implement this feature using the code below, I encountered an error: Uncaught TypeError: Cannot set properties of undefined (setting 'colo ...

    Animating slides with CSS Keyframes and React, incorporating toggle slide fade out and slide fade (back) in

    I am seeking a solution for toggling a box (div) with slide-out animation and then sliding back in animation (in reverse) upon button press. My requirement is to have no animations during the initial page render. While I can successfully slide the box to ...

    I am looking to save a collection of variables in an array and store it as a $_SESSION variable

    Looking to store an array of variables as a $_SESSION variable in order to use it in another .PHP file and perform operations with it. The array: <script> var idArray = [18, 28, 31, 38, 41]; </script> What I attempted, but didn't suc ...

    What are some reasons why the XMLHttpRequest ProgressEvent.lengthComputable property could return a value of

    I've been struggling to implement an upload progress bar using the XMLHttpRequest level 2 support for progress events in HTML5. Most examples I come across show adding an event listener to the progress event like this: req.addEventListener("progress ...

    Is there a way to trigger an AJAX request right before I leave the page or unload it?

    When the window is about to be unloaded, an AJAX request is sent to a specific URL including the recent tracking ID and the time spent on the page in seconds. However, the behavior I am experiencing is an alert displaying [object Object]. ...

    Experience the dynamic bouncing marker feature in Next.js React-Leaflet with the powerful tool Leaflet.SmoothMarkerB

    I'm a beginner in front-end development and I'm attempting to create a bouncing marker in React-leaflet using the leaflet.smooth_marker_bouncing plugin version 1.3.0 available at this link. Unfortunately, I couldn't find enough documentation ...

    a stand-alone Node.js application connecting to a self-signed WebSocket (WSS) server

    I am currently working with a node server (Meteor.js) that needs to communicate with another server using websockets. Since the communication is strictly between servers and does not involve direct users, I have decided to use a self-signed certificate. I ...

    I am encountering a problem while attempting to fetch information from Firestore through the Firebase JS SDK

    My current challenge revolves around retrieving data from Firestore using the Firebase JS SDK. A specific error message persists: An unexpected issue arises: TypeError: firebase_firestore__WEBPACK_IMPORTED_MODULE_3__.getDoc(...).data is not a function I ...

    Developing a standard jQuery function for adding event listeners

    Attempting to replicate the functionality of Google Maps' addListener using jQuery listeners for clicks, keypresses, etc. In Moogle Maps, you can use .event.addListener(map, 'click', function()... or switch 'click' with 'drag ...

    Handling NullPointerException in AngularJs and Jersey when using Java

    I have been tasked with creating an application using AngularJs, Bootstrap, Java, and Tomcat as the server. Even though I am new to Java EE, I am facing an error that seems simple but I cannot find a solution for it. When I initiate the project, I can see ...

    Updating a data table using POST values in ASP.NET: A step-by-step guide

    I am working on updating values in my database and want to ensure that my script is functioning correctly. In order to check, I created a POST method to send the values and confirm they are being received. https://i.sstatic.net/h0IH5.gif Now, my question ...

    Only show the directive methods when using "ng-if"

    I am facing an issue with the Opentoke Library directive, particularly when I use the ng-if. The reason for implementing the ng-if is that WebRTC is not supported on IOS devices, so it displays an alert after the DOM has loaded. <div class="opentok" ng ...

    Chrome's inability to efficiently handle chunked responses in comparison to Firefox and Safari

    I am currently working on a unique test node server that sends chunked responses every two seconds with the specified headers: response.setHeader('Content-Type', 'text/plain') response.setHeader('Transfer-Encoding', 'chu ...

    Managing key presses with functions in VueJs

    Within my component, I am utilizing VueStrap's modal in the following manner: <template> <modal-window v-model="show" v-on:keyup="keyHandler($event)" @ok="submit()" @cancel="cancel()" @closed=" ...

    Switch the background color of a list item according to a JSON search

    Our organization is in need of a feature where members can be inputted into a field and the background color of the parent list item changes based on the name lookup in a JSON file. We are open to a jQuery solution, but JavaScript will also work! You can ...

    Load the dropdown menu in the select element using the AngularJS $ngresource promise

    I have a select box on my webpage that I need to fill with data received from a server. I am currently using a service to fetch this data, but I'm unsure how to access the values returned from the promise and populate the ng-options in the select tag. ...