What is a different way to rearrange items within an Angular Controller without relying on orderBy in the HTML?

http://plnkr.co/edit/apwAQG9tczOUckbc9bya?p=preview

https://i.sstatic.net/NcNYh.png

Seeking to rearrange li elements in the plnkr above without using ng-repeat | orderBy:predicate:reverse syntax in the markup.

The challenge is that new items are dynamically loaded into the list based on various sorting criteria, making it impossible to have a static order.

The current structure of my list:

<ul>
    <li ng-repeat="t in tags" ng-mouseleave="leaveTag(t)">
      <div class="tag-container">
        <div class="tag border1"
             ng-mouseover="showTagDetails(t)">{{t.name}} | {{t.tweets}}</div>
        <tag-details tag="t"></tag-details>
      </div>
    </li>
</ul>

A button I inserted for sorting within the controller:

<button ng-click="reOrderByTweets()">Order by Tweets</button>

The function I'm working on to implement the ordering logic in the controller:

function reOrderByTweets() {
    vs.orderReverse = !vs.orderReverse;
    console.log('vs.orderReverse = ', vs.orderReverse);
}

Answer №1

If you want to filter data in Angular, you can utilize the $filter as explained in the angular docs available here.

Check out this revised version of your Plunkr with a filter implemented in JavaScript.

Personally, I find it more convenient to perform filtering in markup, but the choice is yours as it doesn't impact the outcome.

Don't forget to take a look at the simplified demo below showcasing how filtering works in JavaScript:

angular.module('demoApp', [])
    .controller('mainController', MainController);

function MainController($scope, $filter) {
    var vm = this;
    this.items = [{
        name: 'test1'
    }, {
        name: 'test2'
    }, {
        name: 'test3'
    }];
    this.orderReverse = false;

    this.changeOrder = function () {
        console.log('change order');
        vm.orderReverse = !vm.orderReverse;
        vm.items = $filter('orderBy')(vm.items, 'name', vm.orderReverse);
    }
}
<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">
    <ul>
        <li ng-repeat="item in ctrl.items">{{item.name}}</li>
    </ul>
    <button ng-click="ctrl.changeOrder()">re-order</button>
</div>

Answer №2

If I'm following correctly, the solution is simple:

Controller:

$scope.order = 'tweets';
function toggleOrder() {
    $scope.order = $scope.order === 'tweets' ? '-tweets' : 'tweets';
}

Template:

<li ng-repeat="t in tags | orderBy: order">

Plunker;

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

React-router can manage non-matching paths by utilizing a basic JavaScript router configuration

Is there a way to manage non-matching paths using plain JavaScript in React router configuration? const rootRoute = { component: 'div', childRoutes: [ { path: '/', component: App, childRoutes: [ requir ...

JavaScript barcode data input

I am working with 2 inputs - #barcode and #quantity. When using a barcode scanner, I can easily enter the quantity after scanning data by pressing the Tab key. Typically, the quantity is null, indicating one piece. Currently, my cursor is in the #quantity ...

managing websocket connections across various instances

Looking to grasp the concept of managing websockets across multiple instances in order for it to be accessible by all instances. For example, with three nodes running connected through a load balancer, data needs to be emitted on a specific socket. My init ...

How can I check and add contacts on Telegram?

Assistance needed: I have 40,000 mobile numbers and I need to perform the following tasks: Verify if these numbers have a Telegram account Add these accounts to the contact list Can anyone provide advice on how to accomplish this? Perhaps with examples o ...

The loading indicator fails to show up when users navigate between pages that have already been loaded in NextJS and ReactJS

What do I need: I am seeking a way to show a loading indicator whenever a user switches between pages on my website. After discovering an effective example at https://github.com/zeit/next.js/tree/canary/examples/with-loading, I implemented a similar appro ...

"Automatically insert a new row into the table if the cell loses focus and is not left

Can someone assist me with adding a table row dynamically when a cell is filled and the input focus is lost? My JavaScript skills are not strong. Here is a link to the form: JSFIDDLE <table class="table table-timesheet" ng-controller="TimesheetCtrl"> ...

Is it possible to determine if a JavaScript/jQuery effect or plugin will function on iPhone and iPad without actually owning those devices?

Is there a way to ensure that a javascript/jquery effect or plugin that works well on all desktop browsers will also work on iPhone and iPad without actually owning those devices? Can I rely on testing it on the latest Safari for Windows to guarantee comp ...

Leveraging external data for testing in Protractor script

I am encountering an issue while attempting to access test data using JSON, as it keeps showing up as undefined. I am implementing a Page Object Model and trying to reference external test data. However, when passing the values from my test data into a fun ...

Tips for tallying the quantity of dynamically appended list items on a webpage with jQuery?

Is there a way to accurately count the number of dynamically added list items on a webpage using jQuery? While I can easily count list items that are already present on the page, I am unsure how to do so for items added after the initial load. HTML: < ...

Ways to retrieve the response object from an express application

I am currently working on developing a nodejs application with mysql and my objective is to have my controllers and messages separated into different files. Below are examples of what I am aiming for: First, here is a snippet from my auth controller file: ...

Resizing an iframe dynamically based on the content of the URL without displaying a scroll bar using JavaScript

Within my application, there is a select drop-down menu that contains URLs. When a user selects a URL from the drop-down menu, I want to load that URL in an iframe with the appropriate content size. I am looking for a way to increase the height of the if ...

How does the object scope receive, process, and prepare the update for display within the AngularJs view?

AngularJS allows for data-binding to easily display immediate data in our View. This is made possible by the object scope, which acts as a connector between the Logic Code and The View. Additionally, AngularJs supports two-way binding. My question is: H ...

Unusual behavior observed in Selenium test (Python) when interacting with an Angular JS-based user interface

Currently, we are conducting tests on a web application that is built using AngularJS. I have come across an issue twice so far. This time, I am faced with the task of clicking on a dropdown menu within a link tag. While I can manipulate it manually using ...

How can you generate a Base64 string with Node.js?

I recently utilized the html2pdf npm package to generate a base64 string of a PDF file and then sent it to my Node.js server. I used Nodemailer to send this PDF as an email attachment by configuring the mailOptions object like so: let mailOptions ...

The drop-down button unexpectedly disappears when using Bootstrap in combination with jQuery autocomplete

I have some javascript code that is structured like: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery UI Autocompl ...

I'm curious about the process of uploading an image file to a Mongoose database using the Mean JS

Recently diving into the mean stack, I'm curious about how to efficiently upload an image file to the database using mongoose and angularjs. I've scoured the internet for code examples, but nothing seems to fit my needs. Any guidance or snippets ...

Javascript continues to execute even after the designated element has been eliminated or substituted

I'm currently working on a WordPress auction site using WooCommerce that needs a countdown timer to display when a specific product auction is ending. Below is the JavaScript code for the countdown timer: const getElem = elem => document.q ...

Looping through data in AngularJS with duplicated entries

I'm having an issue with my AngularJS ng-repeat when trying to display JSON data. The records are duplicating, but only after reloading the page. Initially, everything works fine. Take a look at the JSON data below: [{ "EmployeeName": "Jishn ...

Unable to alter the protocol option of the request object in SailsJS

Currently, I am utilizing a library that relies on the req.secure option to proceed without any errors. However, my application is deployed on Heroku and I have implemented custom middleware to check the "x-forwarded-proto" header and set req.secure as tru ...

Angularjs changes the "&" character to "&"

Here is the AngularJS code I am using: $scope.getEventSeconds = function(){ $http.get('myfile.php', { params: { 'action': 'get_datas' } }).success(function(data){ $scope.list = data; $scop ...