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

Importing a JS file within a JS script

Currently, I am facing a requirement to dynamically include a .js file (more jQuery code) within a working jQuery script. Specifically, when my page gets authenticated, I need to add a specific script file. I am looking to accomplish this in ASP.Net MVC. ...

Transitioning from one bootstrap modal to another in quick succession may lead to unexpected scrolling problems

I'm facing a challenge with two modals where scrolling behavior becomes problematic when transitioning from one to the other. Instead of scrolling within the modal itself, the content behind it is scrolled instead. In order to address this issue, I im ...

Save the HTML elements in an object and then use the ng-include directive to include the template

Currently experimenting with this code snippet: var CustomTable = function($elem) { this.properties.element = $elem; this.initialize(); }; CustomTable.prototype.PROPERTIE = { secondElement: $('.second') // this element ...

Combining React with Typescript allows for deep merging of nested defaultProps

As I work on a React and Typescript component, I find myself needing to set default props that include nested data objects. Below is a simplified version of the component in question: type Props = { someProp: string, user: { blocked: boole ...

What is the best way to add a CSS rule to JavaScript?

animation: scaleUp 0.3s linear 0.4s forwards; animation: scaleDown 0.3s linear forwards; Greetings! I'm currently working on adding animations to my content filtering functionality. Specifically, I want to incorporate the aforementioned CSS rules in ...

Updating react state by setting nested objects obtained from a JSON fetch request

I'm currently working on an application that involves fetching recipes from a recipe app. I need to extract specific objects from the JSON data returned by the API and update my state using setState. While I understand how to handle one object, I&apos ...

The functionality of ClickMarker is malfunctioning in the XY Amcharts

Recently, I encountered a situation where I had to incorporate custom legends in XY Amcharts. After managing to implement them successfully, I came across an issue. Despite adding event listeners to the legends, the associated function failed to trigger. ...

Revising variables in Java Script

How can I shuffle a list of variables in JS and maintain the order while changing their values? The following code snippet demonstrates what I am trying to achieve. <p id="demo"></p> <script> var gen = "male "; var race = "white"; var ...

Trading keys between arrays in JavaScript

I have a set of simple objects contained within an array: var myObject1 = [ {name: "value1", adddress: "545454545445"}, {name: "value2", adddress: "323233223"}, {name: "value3", adddress: "332 ...

Is there a way to verify in AngularJS whether ng-model contains a string or a numerical value?

In my Angular application, I have written a JavaScript function that checks if the value of a text field is undefined or empty, and it is working properly. $scope.checkNumber = function(user_answer){ if(user_answer == undefined){ return false; } } My ...

Developing a custom function within an iterative loop

Can someone assist me with a coding problem? I have these 4 functions that I want to convert into a loop: function Incr1(){ document.forms[0].NavigationButton.value='Next'; document.PledgeForm.FUDF9.value='Y1'; document.fo ...

The AddClass function fails to function properly after an ajax form is submitted

I am facing a challenge in setting up validation for my ajax form. My goal is to have a red border appear around the input field if it is submitted empty. Unfortunately, when I try to use addClass(), it does not seem to have any effect. The alert message ...

Associating a variable with a nested scope in AngularJS

I am currently working on a directive that generates a row within a table. To populate the table with this directive row, I am using ng-repeat to loop through a list of items, like so: <tr ng-repeat='item in items' rowItem='item' /& ...

What is the best way to emphasize colors in search results?

Is it possible to assist in highlighting the searched words in yellow? Below is an example of code that filters words from the displayed data from a JSON feed URL. angular.module('sample', []). controller('sampleController', [' ...

Accessing content from a text file and showcasing a designated line

Apologies if my wording was unclear... In this scenario, we will refer to the text file as example.txt. The value in question will be labeled as "Apple" My goal is to retrieve example.txt, search for Apple within it, and display the entire line where thi ...

Guide on creating rsa key pair on the client side with angular2

Is there a way to generate an 'rsa' key-pair on the client-side using angular2? I am looking to create a private/public key pair and store the private key in a database while using the public key on the client side. How can this be achieved? I c ...

Locate the highest and lowest values within a .json file

When working on a graph using d3.js, one key step is setting up the scales for the axis. The data for the graph is stored in a Json file with multiple arrays, each representing different regions and years: [{ "id" : "AustraliaNewZealand" , "year" ...

Oops! Looks like there was an issue with defining Angular in AngularJS

I am encountering issues while attempting to launch my Angular application. When using npm install, I encountered the following error: ReferenceError: angular is not defined at Object.<anonymous> (C:\Users\GrupoBECM18\Documents&bs ...

Utilizing AngularJS "controller as" syntax within templates

Recently diving into the AngularJS world, I embarked on setting up a simple laravel/angular JWT authentication by following this specific tutorial. My goal is to utilize the "Controller As" syntax instead of relying on $scope as instructed in the tutorial ...

Numerous navigable tabs all on a single page

After following a tutorial on YouTube to create scrollable tabs, I successfully implemented it using Bootstrap 5. However, I'm facing challenges in getting multiple scrollable tabs to function on a single page. Although the tabs and tab-content are fu ...