Using method as a filter in AngularJS: A guide to implementing custom filters

I've created a custom data type called Message:

function Message(body, author, date) {
    this.body = body;
    this.author = author;
    this.date = date;
    this.stars = [];
}

Message.prototype.hasStars = function() {
    return this.stars.length !== 0;
};

Currently, I am iterating over an array of these messages:

<li ng-repeat='message in messages | orderBy:"-stars.length"'>…</li>

Is there a way to add a filter that utilizes the message.hasStars() method? I attempted several methods below but none seemed to work as expected:

message in messages | filter:message.hasStars() | orderBy:"-stars.length"
message in messages | filter:message:hasStars() | orderBy:"-stars.length"
message in messages | filter:message.hasStars | orderBy:"-stars.length"
message in messages | filter:message:hasStars | orderBy:"-stars.length"

Answer №1

http://jsfiddle.net/DGKNN/

filter function in AngularJS requires an expression that acts as a predicate on the scope. This means it needs a function that can take an element as input and determine whether or not the element should be included in the collection.

In your controller:

$scope.hasStars = function (message) {
    return message.hasStars();
};

In your view:

<li ng-repeat='message in messages | filter:hasStars | orderBy:"-stars.length"'>...</li>

Answer №2

I assume that a service named mySrv is responsible for loading messages into your controller.

myapp.controller('myCtrlr',['$scope','mySrv',function($scope,mySrv){
    $scope.messages = mySrv.getMessages();
}]); // end myCtrlr

myapp.filter('hasStars',function(){
    return function(msg){
        return msg.stars.length > 0;
    };
});

When working in the template

<ul ng-controller="myCtrlr">
    <li ng-repeat="message in messages | hasStars | orderBy:"-stars.length">...</li>
</ul>

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

Is there a text form in Angular that allows only numerical input?

Here's an input form in Angular that I'm working on: <input ng-model="sc.zip" class="form-control" maxlength="5" type="text" /> I want to keep the form as a simple empty textbox without limiting it to only numbers. However, I do want to r ...

Error Message for Tastypie FormValidation Issue

Within the scope of my current project, I have implemented TastyPies FormValidation for handling ModelResource. However, I am encountering an issue when attempting to transmit invalid data through an AJAX PUT request (utilizing AngularJS). For example: { ...

Can getServerSideProps be adjusted to avoid triggering a complete page reload after the first load?

My server-rendered next.js app consists of a 3-page checkout flow. The first page involves fetching setup data like label translations and basket items within the getServerSideProps function, as shown below: UserDetails.js import React from 'react&apo ...

Tips for activating a function when the sidebar menu is opened in Ionic 2

How can I trigger a function when the SideMenu is open in Ionic 2? I came across this link here for Ionic-1, but I'm wondering how to accomplish this in Ionic 2. Any help would be appreciated. Thanks! ...

PWA JavaScript struggling with GPS geolocation coordinates

I am experiencing issues with the GPS coordinates being stuck when using geolocation in a Progressive Web App (PWA). Sometimes, the coordinates get stuck at the previous location, even if the user has moved since then. I suspect that this is due to the GP ...

Unusual actions exhibited by the jQuery inputs

My form has input fields where jQuery turns a specific input (the URL input) into a link. However, I have two URL inputs with HTML IDs url0 and url1. The issue arises when editing the first input (url0), as the second input (url1) becomes visible and any c ...

Utilizing a dynamic form action connected to an Express route

I've been grappling with creating an HTML form in my nodejs application that directs to the appropriate express route upon submission. After researching online, I stumbled upon a potential solution as outlined below: <script> $('#controlPa ...

Using JQuery to Update Text, Link, and Icon in a Bootstrap Button Group

I have a Bootstrap Button group with a split button dropdown. My goal is to change the text, href, and icon on the button when an option is selected from the dropdown. I am able to change the text successfully, but I'm having trouble updating the HREF ...

Wait for the reaction from react router history to go back

After clicking the submit button in a form, I need to navigate backwards using history.goBack. However, if there is no previous page in the history, I want to redirect to a screen displaying a thank you message using history.replace. const handleSubmit = ( ...

Intensive analysis of objects comparing their characteristics

Currently delving into the world of Javascript, I encountered a coding exercise involving a "deepEqual" function that I attempted to write but ultimately struggled with. Even after reviewing the solution, one particular part perplexed me - the for loop, ...

How can XML data be effectively showcased on a website?

I have a service that generates XML files every 10 seconds with server information. I am seeking a solution to showcase this data on a webpage. After researching online, it appears that utilizing AJAX would be beneficial as it permits the loading of dynam ...

How to deactivate or modify the href attribute of an anchor element using jQuery

My HTML code looks something like this: <div id="StoreLocatorPlaceHolder_ctl07_ctl00_ctl00_pager_ctl00_ctl00_numeric" class="sf_pagerNumeric"> <a href="http://www.domain.com/store-list">1</a> <a href="http://www.domain.com/sto ...

find div elements containing a specific classname

I'm seeking assistance in filtering a large number of populated divs with dynamically generated class names. Here is a form that, when an option is selected, should hide all divs that do not contain the selected class name. <p>To refine your s ...

Exploring the differences: ng-repeat versus md-virtual-repeat

Can you explain the distinction between angular's ng-repeat and angular material's md-virtual-repeat? Under what circumstances would using one over the other be more advantageous? ...

Move the menu button to the right of the title slide, beyond the edge of the card

Having an issue with the MuiCardHeader component. <CardHeader disableTypography avatar={renderAvatar()} action={ <IconButton onClick={toggleMenu}> <img src={MoreIcon} alt=""/> </IconButton ...

Should Jasmine recommend decreasing the number of local variables or focusing on improving karma coverage reports?

My Karma coverage report indicates that the local variable is not being covered. Is this a possible issue with the karma-coverage report? Please take a look at the Angular Controller Code below. 'use strict'; angular.module('moduleName&ap ...

The issue arises when trying to use destructured imports with Mongoose

I've been developing a straightforward Express app with ES6. In the process of creating a schema and model for Mongoose, I encountered an issue with the following syntax: import mongoose, { Schema } from 'mongoose'; const PostSchema = new ...

Refreshing Data in NextJs as Search Parameters Change

I'm currently working on developing an app that features a search bar where users can input a name. The app then queries two different APIs to gather information about that name, displays it to the user, and saves the search along with the results to ...

Having trouble accessing properties within a JavaScript object array in React.js?

I have a React.js component that fetches its initial state data from an API call in the componentDidMount(). This data comprises an array of objects. While I can see the entire array and individual elements using JSON.stringify (for debugging purposes), a ...

React useEffect only retrieves the last element of an array object

I am facing an issue where React seems to only save the last element in my array. Even though I have two elements, when mapping over them, only the last element is being placed in the hook each time. React.useEffect(() => { if (bearbeiten) { handleCli ...