Using AngularJS ng-repeat to apply several custom filters for sorting items based on properties in a JSON object

Link to JSFiddle for this issue: http://jsfiddle.net/ADukg/16368/.

I am attempting to create a filtering system for items in an ng-repeat list based on multiple criteria from the JSON properties of each object.

For example, when the 'Unread' filter is chosen, only items with the 'unread' property set to true should be displayed. Similarly, selecting the high importance filter should show items with the high importance property set to true.

My goal is to have the ability to combine these filters so that only items with both the unread and high importance properties set to true are shown when both filters are applied.

In the provided JSFiddle, I have set up basic models for the filter checkboxes. However, I am struggling with implementing the actual filtering logic for the list. Any guidance on how to achieve this specific scenario would be greatly appreciated.

HTML:

<div>
  <label for="filterByAllCheckbox">Filter by All </label>
  <input ng-model="filters.all" ng-change="filterByAll()" type="checkbox" id="filterByAllCheckbox" ng-disabled="filters.all">
</div>

<div>
  <label for="filterByUnreadCheckbox">Filter by Unread </label>
  <input ng-model="filters.unread" ng-change="manageFilters()" type="checkbox" id="filterByUnreadCheckbox">
</div>

<div>
  <label for="filterByHighImportanceCheckbox">Filter by High Importance </label>
  <input ng-model="filters.highImportance" ng-change="manageFilters()" type="checkbox" id="filterByHighImportanceCheckbox">
</div>

<br>

<ul>
  <b>NOTIFICATIONS</b>
  <li ng-repeat="notification in notifications">
    {{notification.title}}
  </li>
</ul>

Answer №1

To create a similar functionality, you can utilize ng-show within the li element to check for specific conditions (unread and highImportance).

<li ng-repeat="notification in notifications" 
    ng-show="(filters.all) 
    || (filters.unread && !notification.read && filters.highImportance && notification.importance == 'High')
    || (!filters.unread && notification.read && filters.highImportance && notification.importance == 'High')
    || (filters.unread && !notification.read && !filters.highImportance && notification.importance != 'High')
    || (!filters.unread && notification.read && !filters.highImportance && notification.importance != 'High'">
  {{notification.title}}
</li>

However, it's worth exploring other approaches to achieve your desired outcome.

Update: Creating a custom filter implementation.

var myApp = angular.module('myApp',[]).filter('notificationFilter', function () {

    return function (array, all, unread, highImportance) {

        var matches = [];
        for (var i = 0; i < array.length; i++) {
            if (all 
                || (!unread && highImportance && array[i].importance == 'High')
                || (unread && !array[i].read && !highImportance)
                || (unread && !array[i].read && highImportance && array[i].importance == 'High')) {
            matches.push(array[i]);
        }
        return matches;
    };

});

You would then need to invoke the filter within your controller methods.

$scope.manageFilters = function() {
    // Code goes here
}

And

$scope.filterByAll = function() {
    // Code goes here
}

Finally, make sure to update the HTML accordingly:

<li ng-repeat="notification in shownNotifications">
  {{notification.title}}
</li>

Don't forget to include $filter in your controller definition and initialize the list shownNotifications. For further customization of the implementation, feel free to modify as needed.

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

Fetching selenium logs and screenshots from the Intern grid backend

My question pertains to the Intern workflow in case of exceptions, with two specific parts: 1- According to Selenium's Desired Capabilities specifications, RemoteWebDriver automatically captures screenshots on exceptions unless disabled by setting we ...

Oops! The ui-router seems to be having a little hiccup with the animation property not being defined

Upon upgrading my application from angular 1.5.0 to 1.6.5 along with ui-router 1.0.5 (previously using ui-router version 0.2.15), I encountered the error message "Cannot read property '$$animLeave' of undefined". While some routes are functionin ...

When working in JavaScript, the console.log function comes in

Struggling with understanding JavaScript syntax. Can someone explain to me why this line of code works: console.log($rootScope.wg.variable1); But the following line doesn't (resulting in undefined): console.log($rootScope.wg.variable+1); I've ...

Mastering the Art of Binding Variables to Various JSON Types in GOLANG

When it comes to the naming convention of variables in a database, it is customary to use full_name. However, in Postman, the convention dictates using fullName instead. type Person struct { FullName string `json:"fullName"` } Nevertheless, ...

Connecting angularjs's $http.get function with spring's @GetMapping annotation is a simple process that involves properly configuring

$scope.showProjectDetails = function(id){ $http.get('${pageContext.request.contextPath}/api/project', {params: {id}}) .then(function(response){ $scope.projectInfo = response.data; }); } This results ...

Unraveling the mystery: accessing the same variable name within a function in JavaScript

What is the best way to reference the same variable name inside a function in JavaScript? var example = "Hello"; console.log("outside function: " + example) function modifyVariable() { var example = "World!"; console.log("inside function: " + ex ...

How to Preserve Previous Value in a jQuery Change Event for an <input> Element?

Today I spent some time searching for a simple solution, but unfortunately, I have not found one yet. Essentially, what I am trying to do is capture a change in an input element while also being able to retrieve the previous value. Below is a basic exampl ...

Updating NPM packages versions is currently restricted

I'm in the process of creating a Next.JS application using create-next-app. However, I've noticed that in the package.json file it lists the following dependencies: "eslint": "8.43.0", "eslint-config-next": &quo ...

Encountering the error `RollupError: Expression expected` during the compilation of an NPM package

Following the setup of my environment to create my initial NPM package for React JS with ROLLUP bundler, I encountered a RollupError: Expression expected error message as displayed below: Error Message > rollup -c --environment NODE_ENV:development dev ...

<div><!-- including: unknown --></div>

Need some assistance with this issue. The ng-include path I am using is "http://localhost:8080/coffeeprojects/calc.html". I tested the path and it seems to be working. However, despite organizing the files and improving the path as suggested in some resp ...

Can the repeated use of AJAX function calls at regular intervals adversely affect the speed of the application?

On a specific page of my application, I have been using an AJAX function continuously as shown below: <script type="text/javascript"> $(document).ready(function(){ setInterval(function() { $.ajax({ ...

Vue-Routes is experiencing issues due to a template within one of the routes referencing the same ID

I encountered an issue while developing a Vue application with Vue-routes. One of the routes contains a function designed to modify the background colors of two divs based on the values entered in the respective input fields. However, I am facing two probl ...

Oops! There was an error: Uncaught promise rejection: TypeError - Unable to access 'subscribe' property of null object (Ionic Angular)

I encountered an issue in my angular ionic project. When I log in, the first page displays the error "ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'subscribe' of null." However, upon reloading the page, the error disappears ...

Using JavaScript to calculate the difference between the current hour's value and the previous hour's value

Just started experimenting with JavaScript yesterday and was given a small task to create a script for a building controller. The task involves reading values from specific locations, performing energy calculations, and then after 1 hour, subtracting the i ...

Angular 2 and ASP.NET MVC combined application without using Single Page Application techniques

Back in my Angular 1 days, I used to define my app within the body tag like this: <body ng-app="myapp">. This allowed me to load different controllers for various views within my MVC application. For example, I could load one controller in the Home/ ...

What is the ideal number of props to include in a React component?

What is your opinion on the optimal number of props to include in a React component? While I'm aware that there are no strict guidelines regarding this, I would appreciate insights from experienced developers to help ensure clean and easily readable c ...

Parcel-Bundler is unable to resolve critical security issues

I recently followed a tutorial by Kevin Powell on SASS and Parcel through YouTube. I was able to successfully set up the SASS part and get the Parcel bundler working smoothly on one project, so everything seemed to be going well at that point. However, to ...

What is the best way to structure a web server along with a socket.io server?

I am curious about the capabilities of node.js Is it feasible to utilize multiple server.js files? For example, could there be a primary "server.js" that directs users to another directory where a separate server.js manages websocket connections using so ...

PHP and AJAX for streamlined login form experience

Trying to log in through a popup login box using AJAX to determine if the login is successful. If successful, redirect to the header location, otherwise display an error message. Here is the code snippet: <script> $(document).ready(function () { ...