Is there a way to link a number with a particular string and apply that string as a filter for iteration in AngularJS?

I've recently started learning AngularJS and I'm facing challenges with creating a reusable generic filter.

Let's consider the colors, types, and list objects outlined in the new JSON below. I aim to develop a generic filter that can take the colors and types objects to filter the list object without relying on string matching for filtering.

Currently, I have specific filters based on strings as shown below.

As these objects will contain a substantial amount of information, I prefer not to update the controller each time a new property is added to the JSON data.

How can I correlate a number with its corresponding string value?

Old JSON Data

[
    {
        "id": 1,
        "name": "Spike",
        "type": "dog",
        "color": "gray"
    },
    {
        "id": 2,
        "name": "Tom",
        "type": "cat",
        "color": "blue"
    },
    {
        "id": 3,
        "name": "Butch",
        "type": "cat",
        "color": "black"
    }
]

New JSONs - Colors, Types, and Data List

// colors
[
    {"gray": 1},
    {"black": 2},
    {"blue": 3},
]

// types

[
    {"dog": 1},
    {"cat": 2}
]

// data list
[
    {
      "id": 1,
      "type": 1,
      "name": "Spike",
      "color": 1
    },
    {
      "id": 2,
      "type": 2,
      "name": "Tom",
      "color": 3
    },
    {
      "id": 3,
      "type": 2,
      "name": "Butch",
      "color": 2
    }
]

Implemented Filters

        <table class="table table-bordered table-condensed table-striped table-hover">
            <thead>
                <tr>
                    <th>
                        <a>
                            Filters:
                        </a>
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="item in typeItems">
                    <td>
                        <label class="check">
                            <input type="checkbox" ng-model="typeFilterItems[item.type]">{{item.type}}
                        </label>
                    </td>
                </tr>
                <tr ng-repeat="item in colorItems">
                    <td>
                        <label class="check">
                            <input type="checkbox" ng-model="colorFilterItems[item.color]">{{item.color}
                        </label>
                    </td>
                </tr>
            </tbody>
        </table>

Data List Display

        <table class="table table-bordered table-condensed table-striped table-hover header-fixed">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Type</th>
                    <th>Color</th>
                    <th>Name</th>
                </tr>
            </thead>
            <tbody>
                <tr class="list" ng-repeat="item in animals | filter:typeFilter | filter:colorFilter">
                    <td>{{item.id}</td>
                    <td>{{item.type}}</td>
                    <td>{{item.color}}</td>
                    <td>{{item.name}}</td>
                </tr>
            </tbody>
        </table>

Controller Script

    Animals.list().then(function (data) {
        $scope.animals = data;
    });

    $scope.colorFilterItems = { 'black': true, 'gray': false, 'blue': false }; // Initial predefined filter selection 
    $scope.colorItems = [{ name: 'black' }, { name: 'gray' }, { name: 'blue' }];

    $scope.colorFilter = function (item) {
        return $scope.colorFilterItems[item.color];
    };

    $scope.typeFilterItems = { 'dog': true, 'cat': false }; // Predefined filter selection
    $scope.typeItems = [{ name: 'black' }, { name: 'gray' }, { name: 'blue' }];

    $scope.typeFilter = function (item) {
        return $scope.typeFilterItems[item.type];
    };

Answer №1

After receiving no responses, I was able to solve the issue on my own.

The key solution here is utilizing lodash directly within the service and implementing a filter method inside the promise that scans for the chosen property within the filter objects and compares them with the data to be displayed.

filterAnimals = () => {
    intersectedResults =
    _.filter(animals,(animal: iAnimal) => {
        var colors = _.find(colorLabels,(item: iFilter) => {
            return (animal.color ? item.label === animal.color : item.label == null) && item.selected;
        });
        var types = _.find(typeLabels,(item: iFilter) => {
            return (animal.type ? item.label === animal.type : item.label == null) && item.selected;
        });
        return colors && types;
    });
    return data;
};

Following this procedure, I call the filterAnimals() function from the controller and link the checkbox filters to the data. By triggering an ng-change event on the checkbox, this function runs and evaluates the filters against the data, displaying the necessary information.

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

Problem encountered with JQuery Sparkline in Internet Explorer

I recently implemented jQuery sparkline on a webpage, sourced from . However, I encountered an issue with Internet Explorer when the container DIV is not large enough to display it properly. Surprisingly, the code worked perfectly fine in Firefox and Chrom ...

What is the best way to modify a particular value buried within a JavaScript object?

Within my node project, I am working with a JavaScript object like the one shown below: that.responseData = { fields: { id: { label: 'ID', value: objectRecord.id, info: '', ex ...

Attempting to convert a JSON string into a JArray object

Over the last 3 hours, I've been struggling to find a solution on how to convert a JSON string into a JArray to pass it to another method The string in question is: {\"item1\":[{\"id\":\"61578ba2ce164 ...

What could be causing the issue with my confirmation message not working when I attempt to navigate away from the page?

Why is my confirmation message not triggering when attempting to leave the page? <!DOCTYPE html> <html lang="en-US"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <body> & ...

working with the variable returned by an AJAX request

I am facing an issue with my post request to handle a form submission and send an email. This is what my code looks like: $.post(url, data, function(r) { processFormSubmitResult(r); }, 'json'); function processFormSubmitResult(r) { conso ...

Troubles arise when attempting to utilize yarn for my projects

Whenever I enter the command yarn start in the terminal, I get this output: yarn run v1.22.4 $ react-scripts start 'react-scripts' is not recognized as an internal or external command, operable program or batch file. error Command fai ...

Having difficulty sending ajax to the controller function

Currently, I am facing an issue with updating my database using AJAX in Laravel. The goal is to change the value in the enable column from 1 to 0 when a toggle button is clicked. Below script is included in the view: $(".toggle-btn").change(function() { ...

The importance of .hash in this jquery function explained

I utilized a jQuery function from someone else and tweaked it to fit my needs, however, I am struggling to grasp how it actually operates. Specifically, the line var content = this.hash.replace('/', ''); Can anyone offer an explanation ...

Tips for extracting the JSON array nested within a JSON object

Despite having gone through all the previously solved questions related to this same issue, I am still encountering the same error. I am trying to extract the json array "StringValidator" from the example given below: { key: "AppsIds", collectionValidato ...

Kendo sortable interference with input focus

Utilizing both kendo listview and grid components to display the same information in different views; a primary listview of cards and a table-based grid view, both integrated with the Kendo Sortable widget. The objective is to enable users to edit an inlin ...

Navigating with React-router can sometimes cause confusion when trying

I'm having trouble with my outlet not working in react-router-dom. Everything was fine with my components until I added the Outlet, and now my navigation component isn't showing even though other components are rendering. import Home from ". ...

The initial AJAX GET request is successful, however subsequent clicks do not trigger the call

I have been encountering an issue with my JavaScript where an Ajax call that used to work perfectly fine suddenly stopped working. I have not made any changes to the code that could cause this problem, but something is definitely going wrong. The Ajax call ...

Ways to incorporate external JavaScript files into a React component

I have been attempting to incorporate external javascript files into my react component. When I included them in a basic html file using script tags, everything worked smoothly. However, I am unsure of how to achieve this within a react component. < ...

Retrieve information from the index resource using AJAX

I feel like I might be overcomplicating things, but basically, I'm trying to retrieve all the data from an index resource and have it load when a button is clicked using AJAX. I've been using a serializer to tidy up the JSON. Both "/categories" ...

Angular's jQuery timepicker allows users to easily select a

Transitioning from jQuery to Angular, we previously utilized the for selecting times due to Firefox not supporting HTML5 input time. While searching for a similar timepicker plugin for Angular to maintain consistency with our past data and styles, I came ...

Error message "Uncaught in promise" is being triggered by the calendar function within the Ionic

Can someone assist me in creating a calendar feature for my app? My concept involves a button with text that, when clicked by the user, opens a calendar. However, I am encountering an error message: ERROR Error: Uncaught (in promise): TypeError: Cannot set ...

Using various colors to highlight specific sections of a letter or number

I am striving to recreate the unique image shown below, particularly interested in achieving the multi-colored effect on the numbers. This aspect of having different colors for parts of the number is intriguing and I would love to learn how it's done. ...

ensure Selenium waits for animation to finish

I've encountered a problem regarding waiting for an animation to complete. Previously, I could rely on Selenium functions like wait.until(ExpectedConditions.... However, this is no longer sufficient. The element in question can be found in the HT ...

The AngularJS Service fails to update when the user clicks on a link with varying $routeParams

When using a service in angularJS that passes a JSON object to a controller upon clicking a specific link, /match/id-:matchId', it references the $routeParams of the :matchId to determine which JSON object to request. The issue arises when a user cli ...

Is it possible to add to the existing class based on a certain condition?

I have a coding challenge that I need help with. I have a set of code where I want to replace the old value in a class named "content" based on certain conditions. If the value within the class matches one of the values in an Array, then I need to append s ...