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

Refreshing data attribute following an ajax request

I have this page with a list of various job listings. Each job listing has a button labeled "Paid" that includes a data-paid attribute indicating whether the job is paid or not. Whenever the "Paid" button is clicked, it sends a request to my route which u ...

The issue with Express connect-flash only showing after a page refresh instead of instantly displaying on the same page needs to be addressed

Here is the registration route code snippet: router.post("/register", function(req, res){ var newUser = new User({username: req.body.username}); User.register(newUser, req.body.password, function(error, user){ if(error){ req.fl ...

Utilizing an Angular expression within a bespoke directive

Here is the directive that I am currently working with: gymApp.directive('ngListar', function() { return { templateUrl: function(elem, attr){ console.log(attr.type); return 'js/directives/listar-&apos ...

Creating TypeScript modules for npm

I have been working on creating my first npm module. In the past, when I used TypeScript, I encountered a challenge where many modules lacked definition files. This led me to the decision of developing my module in TypeScript. However, I am struggling to ...

How can the background color of a DIV be altered based on the values of an array's minimum

Basically, I am fetching values from an array using AJAX. The background color will change from green to red based on the "aht_value". Currently, the colors are displaying correctly because I hardcoded the values in the calculation below. However, I want t ...

The D3js visualization is failing to display properly for the user, with the D3 source code residing on the server

I have encountered an issue after transferring my D3js chart generation system from a development server with no problems to a live Windows 2008 r2 server. On the live server, only the background SVG element is displayed and none of the other elements like ...

The Jquery script is ineffective for newly added elements

After creating an Ajax Form that functions well, I noticed that when the result of the form is another form, my script does not work for the new form generated. Is there a way to make the new form function like the old one? $(document).ready(function() ...

Issue with jQuery not being able to retrieve the data from my CSS property

this is my custom style code: table.table tr td{ padding:30px; border-left: double 1px white; border-bottom: double 1px white; cursor:cell; } and below is the jQuery script I am using: $(document).ready(function () { ...

Having difficulty in displaying database values in HTML modal using PHP

On my PHP page, I have a setup that displays data based on the fetched id from the URL. Everything is working smoothly, but when I click a button to show a modal with additional information, the modal appears blank. Here is the code snippet I am using: ...

The Iron Seal feature is ineffective when a user tries to log in

Iron.seal isn't properly updating the npm module Iron, which is causing login issues for users. var obj = { a: 1, b: 2, c: [3, 4, 5], d: { e: 'f' } }; var password = 'some_not_random_password_that_is_at_lea ...

The type 'undefined' cannot be assigned to the type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'

Verification Code for JWT This function is used to verify a jwt using typescript. public verify( token: string, secretOrPublicKey?: string | Buffer, options?: jwt.VerifyOptions ): Promise<object | string> { if (!secretOrPublicKey) { ...

Having trouble simulating JavaScript Math.random in Jest?

Math.random() seems to always return random values instead of the mocked ones. script.test.js jest.spyOn(global.Math, "random").mockReturnValue(0.123456789); const html = fs.readFileSync(path.resolve(__dirname, "./script.html"), " ...

Tips for eliminating the glowing effect when pressing down on the thumb of the material ui slider

Visit Material-UI documentation for Slider component. Despite setting the disabled flag for the entire slider, the thumb continues to show a halo effect when clicked. ...

Once the recursive function executes (utilizing requestAnimationFrame), socket.emit can finally be triggered

My current issue involves sending an array to my server from the client side using a recursive function, but the responses from the server are delayed and only arrive after the recursive function completes. I'm uncertain whether the problem lies with ...

Using Javascript, delete all chosen HTML elements containing innerText

Looking to extract certain HTML tags from a block of code in TextArea1 and display the modified output in TextArea2 upon clicking a button. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8&quo ...

Display user information from another component using Vue's dynamic routing feature

In my UserList.vue component, I have a list of users that I want to display on individual user profiles in the SingleUser.vue component. What is the easiest way to achieve this? The user details are stored in the UserList.vue component. When a specific us ...

The curious behavior of ng-class

While experimenting with Angular, I came across an unusual behavior of the ng-class directive. Below is a snippet of my app template: <body ng-app> {{ isSidebarExpanded }} <div ui-view="sidebar" ng-class="{true:'expanded', false:&ap ...

Regular expression pattern for the #include directive

I'm currently developing a node.js JSON tool that involves incorporating external JSON files and merging them after performing nested lookups. I've hit a roadblock with regex patterns needed to validate the following scenarios: !include('oth ...

Make sure to enable contentEditable so that a <br> tag is inserted

When using a contentEditable, it automatically wraps words to create a new line once the width of the editable area is reached. While this feature is useful, I am facing an issue when parsing the content afterwards as I need it to insert a <br> tag ...

Generate and save a document

Upon clicking the button, I am trying to generate a CSV file and download it right away. My current approach is as follows: html: <a class="btn btn-primary" @click="downloadCsv">Download CSV</a> <a v-if="fileObjectUrl !== null" ref="down ...