Angular sorting data is not functioning as expected

I've been attempting to utilize AngularJS to organize my data, but unfortunately, it seems to be ineffective.

I am fetching data from Firebase () and using Node.js to transmit it to a controller.

Controller Code

var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {

// Pulls list of games
$scope.pullGame = function() {
  console.log("Here");
  $http.get('/getGameData').success(function(response) {
    console.log(response);
    $scope.championlist = response;
  });
};  
}]);

Then I am displaying the information using ng-repeat

<!DOCTYPE>
<html ng-app="myApp">
<head>
    <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<title>DevCha</title>
</head>
<body>
<div class="container"  ng-controller="AppCtrl">

<input class="form-control" ng-model="game.name">
<button class="btn btn-info" ng-click="pullGame()">Update</button>

<h1>DevCha</h1>

<table class="table">
    <thead >
    <tr>
        <th>Champion Name</th>
        <th>Wins</th>
        <th>Losses</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="champion in championlist|orderBy: 'name'">
        <td>{{champion.name}}</td>
        <td>{{champion.wins}}</td>
        <td>{{champion.losses}}</td>
    </tr>
    </tbody>
</table>
</div>

<script src="controllers/controller.js"></script>

</body>
</html>

I have attempted to use Firebase to sort the data without success, which is strange. I am open to either Angular or Firebase helping me sort the data.

Node.js code that sends the data to Angular

app.get('/getGameData', function(req, res){

    var ref = new Firebase("https://boiling-inferno-4886.firebaseio.com/champion");

    ref.once("value", function(snapshot) {
      // Success
      console.log(JSON.stringify(snapshot.val()));
      res.json(snapshot.val());

    }, function (errorObject) {
      console.log("The read failed: " + errorObject.code);
      //callback("Failure", null);
    });

});

Sample_Data - 1: {name: 'Jim', Wins: 10, Losses: 5}, 2: {name: 'Fred', Win:8, Losses: 5} (Actual data can be found at the firebase link)

tl:dr I need to sort my data, I have tried using Firebase's built-in methods and Angular's | orderBy, but neither are working

Answer №1

We really need to analyze that information, but since I've encountered this issue in the past, here is my solution.

If you refer to the documentation, you'll see that the orderBy function only orders arrays. The (key, value) syntax is designed for objects. Perhaps converting your dictionary into an array could solve the problem.

If not, you can create a custom filter to handle this. You can take a look at the following filter:

app.filter('orderObjectBy', function () {
  return function (items, field, reverse) {
    var filtered = [];
    angular.forEach(items, function (item) {
        filtered.push(item);
    });
    filtered.sort(function (a, b) {
        return (a[field] > b[field] ? 1 : -1);
    });
    if (reverse) filtered.reverse();
    return filtered;
  };
});

You can then apply the filter like so:

<div class="item" ng-repeat="item in items | orderObjectBy:'position'">

</div>

Additionally, you have the option to adjust the ordering like this:

<ul>
  <li ng-repeat="item in items | orderObjectBy:'color':true">{{ item.color }</li>
</ul>

Remember, 'false' represents ascending order and 'true' represents descending order.

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

Load page content dynamically with Ajax in a specific div while still allowing the option to open the content in a new tab by right-clicking

As I work on developing a new website that utilizes a MySQL database to sort various items into categories and subcategories, I have implemented a script that dynamically loads category content into a div without requiring a page reload. This seamless load ...

Searching for different forms of multiple words using regular expressions

I have a value saved in a variable: var myvalue = "hello bye"; var myText = "hellobye is here and hello-bye here and hello.bye" Is there a way to check if different versions of myvalue are present in the text? I am currently using this pattern: hello ...

Transform the Node.js requests for both GET and POST methods to utilize Ajax

I am new to JavaScript and am currently learning how to send requests from a Node.js backend using Ajax for GET/POST operations. My backend is connected to a MySQL database and I have been studying some tutorials to gain a better understanding. Here is an ...

Using ngBindHtml in combination with angularUI in a template may yield a different outcome compared to using $sce.parseAs

Edit: Problem solved! Details at the end of the question. Within my directive sfNgFieldWrapper, I have integrated a tooltip from angularjUI ui-bootstrap. The text for the tooltip is designated by tooltip="{{ttpText}}". The issue arises when the text con ...

Is there a way to extract individual values from a for-each loop in JavaScript?

Would appreciate any guidance on my use of Bootstrap vue table with contentful's API. I'm currently working on implementing a for loop to iterate through an array and retrieve the property values. Although the console.info(episodes); call success ...

What is causing this form to submit?

I need help with sending emails via AJAX. My problem is that the form keeps submitting and refreshing, even though I haven't used GET to send anything in the URL. HTML: <form onsubmit="ajaxEmail(); return false;" > <input type=" ...

How can you turn off the full-page display of Javascript errors in Visual Studio?

Recently, I've been experimenting with React on Visual Studio using a React app and C#. However, I find it frustrating that JavaScript errors are displaying as full pages instead of in the console. Is there a way to turn this feature off? I've s ...

Exploring the syntax for navigating with JS Angular and HTML, such as when using the code snippet: ng-click="save(userForm)"

I am struggling to grasp the functionality of a specific part of this code. Despite my efforts to find tutorials, I have been unable to locate relevant information. There are two lines in particular that puzzle me: <button type="submit" class="btn btn ...

The v-show directive is not activated by a Vuex commit

I am experimenting with vuex for the first time, and I have come across an issue where a v-show directive is not triggering after a mutation commit on the store. // store.js import Vue from "vue" import Vuex from "vuex" const states = ...

How can I remove a row from a JavaScript array based on the value of the first item in the row?

Creating an array in JavaScript can be done like this: var myArray = new Array(); myArray.push({ url: urlValue, filename: fileNameValue }); As time goes on, the array will accumulate various items. If you need to delete a specific row based on the urlVal ...

C# - Issue with Webbrowser failing to fully load pages

I am facing an issue with loading pages completely on the web browser, likely due to heavy usage of JavaScript. To address this problem, I have integrated another browser into the project called Awesomium. I am wondering if Awesomium supports using getEle ...

Creating a Vue component using v-for and a factory function allows for dynamic

I am currently developing a Table component using factory functions for all logic implementation. Within a v-for loop, I generate a cell for each item in every row. The factory Below are the actual factories that I import into the respective vue page whe ...

Instruments for crafting an application compatible with a wide range of web browsers

Currently tackling various browser challenges. I find myself wondering whether it's achievable to create an application that is compatible with all browsers, or at least the majority. Should it be a web application? Any recommendations on frameworks a ...

Issues with select options not functioning correctly in knockout framework

Currently, I am engaged in a project where data is being retrieved from an API. The main task at hand is to create a dropdown list using select binding. In order to do so, I have defined an observable object to hold the selected value within my data model. ...

"The controller's $scope isn't being updated within the DIV following a routing change

My website contains ng-view partials that change based on routing updates in $routeProvider. anmSite.config(function($routeProvider, $locationProvider){ $locationProvider.html5Mode(true); $routeProvider //Home page route .when("/", { temp ...

Preventing Redundancy in Angular 2: Tips for Avoiding Duplicate Methods

Is there a way I can streamline my if/else statement to avoid code repetition in my header component? Take a look at the example below: export class HeaderMainComponent { logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts @Vie ...

The JavaScript code is failing to retrieve any data from the API

import React, { Component } from 'react'; export class FetchData extends Component { static displayName = FetchData.name; constructor(props) { super(props); this.state = { users: [], loading: true }; } componentDidMount() { ...

Getting elements in order with bootstrap

Can you help me align the "Format Example" string with the textual labels of the input fields without using static width in AngularJS with Bootstrap? The current alignment is right-justified but I would like it to be more dynamic as shown in the screenshot ...

Leverage the power of Shopify API to retrieve a list of all products by making a request through

My website is custom built on node.js, and I am looking to retrieve all of my products in a single GET request. Unfortunately, the Shopify buy-button feature does not allow me to display all products at once due to pagination, hindering my ability to effec ...

Equalize the color of overlapping background events with non-overlapping background events in fullcalendar

events:[ {overlap:false, display:'background', start:'2021-12-23 10:15:00', end:'2021-12-23 10:30:00'}, {overlap:false, display:'background', start:'2021-12-23 10:30:00', end:'2021-12-23 10:45:00&a ...