Customizing order and limit features in AngularJS

I have a collection of items that I need to organize into separate lists based on priority levels.

items = [
    {'type': 2, 'priority': 1, 'name': 'one'},
    {'type': 1, 'priority': 2, 'name': 'two'},
    {'type': 1, 'priority': 3, 'name': 'three'},
    {'type': 1, 'priority': 4, 'name': 'four'},
    {'type': 1, 'priority': 5, 'name': 'five'},
    {'type': 2, 'priority': 6, 'name': 'six'},
]

Using ng-repeat, I want to sort these items by priority and group them by type. Each list should have a maximum sum of 4 for the type values. The final output should be as follows (sorted by name)

['one', 'two', 'three', 'four']
['five', 'six']

Answer №1

To implement sorting and grouping in JavaScript, leverage the power of Underscorejs as shown below:

var sortedItems = _.chain(items).sortBy('priority').groupBy('type').value();

You can then easily iterate over the new array using ng-repeat directive.

UPDATE: Check out the working example on jsfiddle: http://jsfiddle.net/abcd1234/

Answer №2

Utilizing a specialized Angular filter, you have the ability to easily filter your ng-repeat as demonstrated below or on this jsfiddle.

Instead of utilizing a forEach loop, another option would be to implement a lodash or underscore method (such as groupBy('type').

Angular filters also provide an alternative approach, as showcased in this jsfiddle, eliminating the need for a custom filter.

angular.module('demoApp', [])
    .filter('filterByType', TypeFilter)
    .value('MAX_ITEMS', 4) 
    .controller('mainController', MainController);

function TypeFilter($filter, MAX_ITEMS) {
    return function(input, selectedType) {
        var out = [], count=0,
            ordered = $filter('orderBy')(input, 'priority');
        //console.log("filter start", ordered);
        
        angular.forEach(ordered, function(obj, index) {
            if ( obj.type == selectedType.type && 
                count < MAX_ITEMS ) {
                out.push(obj);
                count++;
            }
        });
        //console.log(out);
        return out;
    }
}

TypeFilter.$inject = ['$filter', 'MAX_ITEMS'];

function MainController() {
    
    this.filterTypes = [
            {type: 1},
            {type: 2}
        ];
    this.type =  this.filterTypes[0];
    this.items = [
        {'type': 2, 'priority': 1, 'name': 'one'},
        {'type': 1, 'priority': 2, 'name': 'two'},
        {'type': 1, 'priority': 3, 'name': 'three'},
        {'type': 1, 'priority': 4, 'name': 'four'},
        {'type': 1, 'priority': 5, 'name': 'five'},
        {'type': 2, 'priority': 6, 'name': 'six'},
    ];
     
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="mainController as ctrl">
    Filter by type:
    <select ng-model="ctrl.type" ng-options="opt.type for opt in ctrl.filterTypes"></select>
    <p>selected type: {{ctrl.type.type}}</p>
    <ul>
        <li ng-repeat="item in ctrl.items |filterByType:ctrl.type">
            {{item.name}}
        </li> 
    </ul>
</div>

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 reason behind Angular not allowing users to define @Output events that begin with 'on'?

While developing a component, I defined an output EventEmitter named onUploaded. However, Angular flagged an error instructing me to use (uploaded) instead. This restriction is due to security concerns, as bindings starting with 'ono' pose risks. ...

Increase the number of key-value pairs within the elements of an array using PHP

If I have an array with the initial element: Array ( [name] => John Doe [occupation] => engineer ) Now, I want to add more properties so that the final result looks like this: Array ( [name] => John Doe [occupation] => engineer [skill] => ...

Having trouble with Vue's $route.push method not working when invoked from a method?

I am currently in the process of creating a search bar for my application using the vue-bootstrap-typeahead autocomplete library. For those unfamiliar, when an option is selected from the suggestions list, it triggers the @hit event which passes the result ...

What is the best way to send a POST request with parameters to a PHP backend using AJAX?

This is an updated version of a previous question that was identified as a duplicate (How can I send an AJAX POST request to PHP with parameters?) I am currently sending an AJAX request to a PHP backend. Here are the JavaScript functions used to make and ...

Is it possible to retrieve specific elements from another html file using AJAX?

Looking to use vanilla JS for loading content dynamically without needing a page refresh. The goal is to retrieve content from another HTML file when a menu option is selected, while targeting either the body or a specific class. Is it possible to achieve ...

Load elements beforehand without displaying them using a div

In order to efficiently manipulate my Elements using jQuery and other methods, I am exploring the idea of preloading them all first. One approach I have considered is creating a div with CSS display set to none, and placing all the elements I need for my w ...

Issue with rendering Base64 image array strings in FlatList component in React Native

In my RN App, I am trying to display a FlatList with Image Items but it seems like I have missed something. I am retrieving blob data from my API, converting it to a String using Buffer, and then adding it to an Array. This Array is used to populate the F ...

JQuery UI autocomplete vanishes instantly without any warning

I am encountering an issue with JQuery UI's autocomplete feature where the dropdown results do not stay visible. While debugging, I noticed that the list briefly appears before disappearing. Below is my code snippet: HTML: <input type="text" plac ...

"PHP, AJAX, and JavaScript work together to run a loop that processes only the final element

Hello everyone, I need assistance in saving data from a loop. Here is the code snippet that I am working with: <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> ...

Utilizing MongoDb and Node.js for efficient data input

I am currently facing an issue while trying to input data into a mongodb collection using node.js. I believe I have the necessary access to the collection in question. var collection = db.collection("whatsGoingOnEvents"); if(collection){ console.log("hitt ...

When a user clicks on a child element in ReactJS, the onclick event returns as undefined

I am experiencing an issue with my restaurants list component. While I have an onClick event set up for each list item, clicking on a child element of the list item does not trigger the expected response. When this occurs, nothing happens or I see an undef ...

highlight the selected option in the ng-repeat list of items

Looking for some assistance with a coding problem I'm having. I keep running into an error when trying to make a selected item in an ng-repeat list highlight. The CSS style is only applied on the second click, not the first. Additionally, I need to en ...

NodeJS CORS functionality failing to function properly in the Google Chrome browser

In my nodejs script, I have implemented CORS as shown below: var express = require('express') , cors = require('cors') , app = express(); app.use(cors()); To fetch JSON data from another domain, I am using an AJAX request. While ...

Exploring the Difference Between $onChanges and $onInit in Angular Components

What sets apart the use of Controller1 compared to Controller2? angular.module('app', []) .component('foo', { templateUrl: 'foo.html', bindings: { user: '<', }, controller: Controller1, ...

How to use AngularJS to collapse various panels with unique content

Hey everyone, I'm working on developing a collapsible panel using Angular. The panel should consist of a header and body to display the content. The desired behavior is that when a button is clicked, the content collapses down, and clicking the same b ...

Make this array output from PHP easier to understand by simplifying it

I'm facing difficulties with the formatting of my JSON data. Here is the structure of my script: $array1 = array(); for($i = 0; $i < 2 ; $i++) { $array1[] = array ( "stocks" => array ( "0" => "apple", "1" => "banana", ...

Monitoring Clicks within an Iframe

Is there a way to track a click event on a hyperlink within an iframe using Google Analytics? The iframe is located within the same domain as the main page. How can this be achieved? The iframe is added dynamically to the page after it has loaded. Is i ...

"Unusual HTML and jQuery quirk causing a perplexing issue: a function that keeps looping inexp

A unique code written in javascript using jQuery allows users to create a "box" on a website with each click of a button, triggering an alert message upon clicking the box. The process is as follows: 1) Clicking the "Add (#addBox)" button appends a new li ...

Using Jquery and css to toggle and display active menu when clicked

I am trying to create a jQuery dropdown menu similar to the Facebook notification menu. However, I am encountering an issue with the JavaScript code. Here is my JSFiddle example. The problem arises when I click on the menu; it opens with an icon, similar ...

The interval keeps resetting every time I want the initial one to expire first

I'm currently working on a battle system that utilizes intervals, and I've encountered an issue where it keeps refreshing instead of creating multiple intervals. When I stop pressing the button associated with it, everything goes back to normal. ...