Sorting and filtering data using AngularJS filter and orderBy inside a controller or factory

I am currently working with a factory that looks like this:

app.factory("ModuleFactory", function (api, $http, $q, filterFilter) {
var moduleList = [];
var categoryList = [];
var moduleTypeList = [];
var academyModuleTypeList = [];
var mostUsed = [];
var lastUpdated = null;
return {
    /**
     * @description This function retrieves the complete module list for the organization of the user.
     * @author Marc Rasmussen
     * @returns {d.promise}
     */
    getList: function () {
        var d = $q.defer();
        if (moduleList.length == 0) {
            $http.get(api.getUrl('module', null))
                .success(function (response) {
                    moduleList = response;
                    lastUpdated = new Date();
                    d.resolve(response);
                });
        }
        else {
            d.resolve(moduleList);
        }
        return d.promise;
    },
    getMostUsed: function () {
        var d = $q.defer();
        if(moduleList.length <= 0){
            this.getList().then(function () {

            })
        }
    }
}
});

Now, the moduleList includes a collection of objects, each containing a field called num_used.

You'll notice I've created a function named getMostUsed. What this function should do is return the moduleList sorted in descending order based on the num_used field.

Although I could use array.sort(), I'm interested in leveraging the power of an Angular function like filterFilter to achieve this. Can anyone provide guidance on how to accomplish this?

Answer №1

If you have created a custom filter called filterFilter, you can easily use it in your controllers or factories within your app.

First, make sure to import the Angular $filter service into your code.

app.factory("ModuleFactory", function(api, $http, $q, $filter) {

To utilize your custom filter when needed, simply call it like this:

 $filter("filterFilter")(moduleList);

For more information on using the $filter service in Angular, refer to the documentation page here.

If you wish to sort your moduleList based on a specific property, consider using the orderBy filter.

this.getList().then(function(moduleList) {
  $filter('orderBy')(moduleList, '-num_used'); // order descending by the num_used property
})

Find more details about the orderBy filter in the Angular documentation here.

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

"I am encountering an issue where I am using React and Express to retrieve data from a database, and although I am able to return an array of

I am working on a React app that communicates with an API using Express. Currently, I am using the GET method to fetch data from a database, and my fetching code looks like this: const posts = []; fetch(URL) .then(response => response.json()) .then(jso ...

Using query parameters in Angular to interact with APIs

One scenario involves a child component passing form field data to a parent component after a button press. The challenge arises when needing to pass these fields as query parameters to an API endpoint API GET /valuation/, where approximately 20 optional p ...

My goal is to display the products on the dashboard that have a quantity lower than 10. This information is linked to Firestore. What steps can I take to enhance this functionality?

{details.map((val, colorMap, prodName) => { I find myself a bit perplexed by the conditional statement in this section if( colorMap < 10 ){ return ( <ul> <li key= ...

Running the command "npm start" in ghost (node.js) is causing an error

After successfully installing node.js, I attempted to set up Ghost. However, when running the installation for Ghost using npm install --productions I encountered the following error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" da ...

Finding the Right Path: Unraveling the Ember Way

Within my application, I have a requirement for the user to refrain from using the browser's back button once they reach the last page. To address this, I have implemented a method to update the existing url with the current page's url, thereby e ...

Clearing the filename in a file type input field using React

When using this input field, only video files are accepted. If any other types of files are uploaded by enabling the "all files" option, an alert will be displayed. While this functionality is working correctly, a problem arises if a non-video file is adde ...

dc.js bar graph bars blending together

This datetime barChart is causing me some trouble. Interestingly, when I try to replicate the issue in a fiddle (check here), everything functions as expected. Please note that the data takes about 30 seconds to load from github. Below is the code for the ...

Is there a way to extract just the first line or n characters from a JSON file without having to download the entire dataset?

I am looking to extract specific information from a large JSON file that is 450 KB in size. However, I do not need to download the entire JSON file as I only require certain characters or lines from it. Is there a way to read n characters or line by line ...

What is the best way to fetch the title property from my Campaign Contract for displaying it in the render method?

I'm currently working on a unique crowdfunding DApp that requires constant access to contract variables through function calls for retrieval purposes. The getDeployedCampaigns function is responsible for returning an array of deployed campaign addres ...

Having trouble obtaining information from the state with Pinia Store

Currently, I am delving into the world of the composition API and Pinia with Vue3. I am facing an issue while calling an external API to fetch data and store it in the state of my store. The problem arises when I try to access this state from my page - it ...

When the second click triggers the loading of a JSON lot via AJAX

As a newcomer to jQuery and ajax, I am in the process of developing an application where content is loaded from a JSON file based on the navigation option selected. Here is the code snippet I've been working on: $(document).ready(functi ...

Ensuring the accuracy of nested objects through class validator in combination with nestjs

I'm currently facing an issue with validating nested objects using class-validator and NestJS. I attempted to follow this thread, where I utilized the @Type decorator from class-transform but unfortunately, it did not work as expected. Here is my setu ...

The JS copy function is successful when operating on a single element, but it encounters issues when attempting to run on multiple elements, only copying

My code includes a copy function that copies the data from a textarea to the clipboard when a button is clicked. The functionality works perfectly for the first textarea, but for subsequent textareas, the buttons do not perform the copy action. Check out ...

npm encountered an error or issue during the installation process

I have configured my proxy settings in the .npmrc file, but I am encountering errors when running the npm install command: $ npm install npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program File ...

Sharing a state object with another React file can be accomplished by using props or context to

My first React file makes an API call to retrieve data and save it in the state as Data. import React, { Component } from "react"; import axios from "axios"; import Layout from "./Layout"; class Db extends Component { constructor() { super(); th ...

Reset the select boxes when a button is clicked

I'm currently utilizing Devextreme within my Angular application, and I have three dx-selectbox elements in the component. I am attempting to clear all three dropdown selections when clicking a "clear" button. Unfortunately, I am unable to find a way ...

Tips for creating a blur effect on all options except for the selected 2 out of 4 using jQuery

My goal is to choose 3 options from a list and once 3 options are selected, all other options will be blurred to prevent further selection. Please review the code snippet I have provided below. Link to File <!DOCTYPE html> <html> <head> ...

Discovering the Firefox Add-on Bar's Height utilizing Javascript

Did you know that Firefox's Addon toolbar can vary in size depending on whether text is displayed along with icons? Is it feasible to determine the exact height using javascript? ...

Datepicker directive malfunctioning due to ng-model issue

I am utilizing a directive to initialize a datepicker, which is appended to the input tag. However, I am facing an issue where the ng-model in the directive does not bind the selected date from the datepicker. Below is the code snippet for the directive: ...

What could be the reason behind ng-bind-html only displaying text and not the link?

Utilizing ng-repeat to exhibit a list on my webpage. One of the fields in my data contains a URL that I want to display as an actual link within my HTML page. Please refer to the screenshots below: My HTML: My rendered page: I have included the angular- ...