Leveraging a function for filtering in AngularJS

I have developed an application where the content filter changes depending on which button is clicked. I have managed to figure out the straightforward filters, but now I am attempting to create a filter that displays content within a specified range.

Below is the function I am using:

$scope.isGood = function(item){
    if(!isNan(item.rating)){
        return (item.rating>49);
    }
    return alert("Something broke!!");
    //returns true if the item has a high rating (is good, 50+)
    //returns false if the item has a poor rating (is bad, 49-)
}

As the filter changes based on the navigation button clicked, and the navigation is dynamic, for each navigation button click, I execute a function that retrieves the filter from its link.filter section and assigns it to $scope.selectedFilter, a variable used in my ng-repeat like this:

<tr class="progress" ng-repeat="idea in ideas | filter:selectedFilter">

Considering I have multiple filters, instead of injecting my own $filter and needing to chain them together, I intend to write something that can fit into the $scope.selectedFilter variable since only one filter should be active at a time.

Here is an example of how the dynamic navigation is structured:

$scope.links = [
    {'name':'About',
    'URL': '#/about',
    'filter':'' 
    },
    {'name':'Active',
    'URL': '#/active',
    'filter': {active: true}  
    },
    {'name':'Inactive',
    'URL': '#/active',
    'filter':{active: false}
    },
    {'name':'Good Rating',
    'URL': '#/active',
    'filter': 'isGood(item.rating)' 
    },
    {'name':'Bad Rating',
    'URL': '#/active',
    'filter':'!isGood(item.rating)'
    }
];

Below is the content I would like to filter:

$scope.ideas = [
    {'title':'Title A',
    'rating': 80,
    active: true
    },
    {'title':'Title B',
    'rating': 55, 
    active: false
    },
    {'title':'Title C',
    'rating': 10, 
    active: true
    }
];

Despite my efforts, I am unable to get the filter to work, and I am uncertain about where I might have made a mistake. As I am relatively new to Angular, could there be an error in my syntax somewhere? I tried following the structure ofthis answer, but no success.

I would greatly appreciate any assistance. Thank you!

Answer №1

The issue here lies in the fact that the filter value was set as a string instead of an actual function. It needs to be a proper function in order to work correctly. This function can then utilize the isGood function as needed. To resolve this, you should update your code like so:

{
   'name': 'Good Rating',
   'URL': '#/active',
   'filter': function(item) {
      return $scope.isGood(item.rating);
    }
}

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

What is the best method for arranging checkboxes in a vertical line alongside a list of items for uniform alignment?

Trying to come up with a solution to include checkboxes for each item in the list, maintaining even vertical alignment. The goal is to have the checkboxes in a straight vertical line rather than a zigzag pattern. Coffee Nestle ...

What does Angular classify as a watcher?

What qualifies as "watchers" within Angular? Are watchers the only type of monitoring mechanism, or do other Angular elements like ngModel also serve as watchers? Am I overlooking something crucial? For example, do watchers play a role in enabling directi ...

What causes an error when attempting ++[] but produces 1 with ++[[]][0]?

Can you explain the difference between the following two expressions? It appears that incrementing [] is equivalent to incrementing [[]][0] since the first element of this outer array is []. console.log(++[]); console.log(++[[]][0]); ...

Issue with click event not being triggered in Kendo Sortable and AngularJS combibation

Check out this plunk where I have a directive containing a KendoSortable. I'm facing an issue where the click event is not triggered when the user clicks on any of the sortable divs. Can you spot what's causing the problem in the code? HTML < ...

Building an expansive navigation menu with react-bootstrap

My current project involves creating a mega menu. Although I successfully made a responsive navbar, the challenge now is to implement a dropdown panel with 100% width. I've tried various approaches but haven't found one that works. Note: The oth ...

Is it possible to load images top to bottom?

Is there a way to make browsers load images from the bottom to the top? Imagine I have an extremely long image that takes 60 seconds to load. The content is designed to be read from bottom to top. Is there any trick I can use to ensure that the image load ...

Error: The server is unable to process the POST request to /api

Currently following a tutorial on YouTube: https://www.youtube.com/watch?v=4ECVE6TXKLQ&list=PLI-gk4ISRzCPlJjCz3yuAhL8vnmK6KWr7&index=11 After setting up a server listening on port 8080 and connecting to MongoDB Atlas successfully, the next step ...

AngularJS seems to be ignoring CSS styles when displaying list items in the ng-repeat loop

After coming across a tutorial on creating round circles connected by a line in CSS, I decided to implement it myself. Interestingly, everything worked perfectly fine when I tested it with static HTML. However, when I tried to make it dynamic using Angular ...

Is it possible to add information to the form data object?

When I send an image to the server using form data, everything seems fine until I try to add data from a crop plugin. Here is the code snippet: //create form data from form var formData = new FormData($('#my-form')[0]); //append the image formD ...

Use two fingers to scroll up and down on the screen

I am currently developing a sketch web application (using angular) that utilizes one finger gestures for drawing. My goal is to enable vertical scrolling in the sketch content by using two fingers. However, when attempting to scroll with two fingers, Safa ...

Interacting between Angular controllers and directives while maintaining separation of concerns

In my AngularJS project, I've implemented a directive within a module named ThreeViewer that displays WebGL scenes based on the specified source file. The code snippet below outlines the basic functionality: angular.module('ThreeViewer', [] ...

What is the best way to create three distinct fractions in JavaScript that cannot be simplified?

I have a specific requirement to create 3 fractions with the following conditions: The denominator remains constant The numerator must be unique and fall within the range of 1 to three times the denominator The fraction should not be reducible (e.g., 2/6 ...

AngularJS application, when making a CORS GET request, is not transmitting HTTP headers

My issue lies in the fact that when making HTTP GET requests in AngularJS, the headers are not being sent. Strangely enough, for HTTP POST requests, the headers are properly set. These requests are made over CORS. Despite scouring numerous posts on StackO ...

Experimenting with ES6 modules using Mocha

Recently, I was given a new project at work that involves using raw native imports/exports in code (compatible only with the latest browsers). The project is being worked on by consultants, and although I cannot make significant changes to their work, I am ...

TinyMCE: Tips for adding and highlighting text in your content!

Is there a way to insert, or even replace the current selection with some content and then have it automatically selected? Take for instance this text: Hello nice world! The user has selected nice. After clicking a button, this code is executed: editor. ...

Modify variables in the child function to be utilized in the parent function

I need to create a scenario where a variable defined in a parent function is modified within a child function and then returned back to the parent as an updated variable. Here is the code I have attempted: let value = 20; console.log(value); // Output: ...

Exploring and extracting values from nested arrays of objects in JavaScript and React

Hey there, I am having trouble getting the data from the backend server to display on a chart library. Can you please take a look at my code and help me out? const data = [ { id: "americano", data: [{x: "10",y: 10,}, {x: &quo ...

The program encountered an error while trying to access the undefined property '_header'

An issue arises when the app.use(express.static("web")) line is executed. var express = require('express')(); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); //app.get(&apo ...

Setting up django alongside angularjs for deployment

This is the structure of my application: myapp --backend --env --frontend -- .idea -- app -- assets -- bower_components -- views -- .htaccess -- index.html -- node_modules flag I utilized Django as an API to return JSON objects and cons ...

Adding a specialized loader to vue-loader causes issues when the template contains personalized elements

My vue2 component is structured as follows: <template> <p>Hello world</p> </template> <script> export default { name: 'Example' }; </script> <docs> Some documentation... </docs> In addition, I& ...