Arranging an array of objects by a specific property in an Angular controller with the help of $filter

In my data set, there is an array of objects referred to as $scope.segments, which looks like this:

[
  {
    "_id": "55d1167655745c8d3679cdb5",
    "job_id": "55d0a6feab0332116d74b253",
    "status": "available",
    "sequence": 1,
    "body_original": "Such a fork",
    "__v": 0,
    "body_translated": "Tal bifurcación"
  },
  {
    "_id": "55d1167655745c8d3679cdb4",
    "job_id": "55d0a6feab0332116d74b253",
    "status": "available",
    "sequence": 0,
    "body_original": "So this is it.",
    "__v": 0,
    "body_translated": "Así que esto es."
  }
]

To rearrange this array based on the 'sequence' property in ascending order (starting with sequence 0), I am using the following code snippet inside a view:

<ul ng-repeat="segment in segments | orderBy: 'sequence'">
    <li>{{ segment.sequence }}</li>
</u>

However, when attempting to apply the orderBy filter within a controller using the code below:

$scope.test = $filter('orderBy')($scope.segments, 'sequence');

The result appears to be an empty array ([]). This suggests that the $filter function may not be functioning properly within the controller.

If you have any suggestions or insights on resolving this issue, I would greatly appreciate your input. Thank you!

Answer №1

It seems like there might have been an issue with properly injecting the $filter service into your controller, as this solution worked for me.

<body ng-controller="MainCtrl">

  <ul ng-repeat="segment in segments | orderBy: 'sequence'">
    <li>{{segment.sequence}}</li>
  </ul>

  <script src="vendors/angular.min.js"></script>

  <script>
    angular.module('app', [])

    .controller('MainCtrl', ['$scope', '$filter', function($scope, $filter) {
      $scope.segments = [
      {
        "_id": "55d1167655745c8d3679cdb5",
        "job_id": "55d0a6feab0332116d74b253",
        "status": "available",
        "sequence": 1,
        "body_original": "Such a fork",
        "__v": 0,
        "body_translated": "Tal bifurcación"
      },
      {
        "_id": "55d1167655745c8d3679cdb4",
        "job_id": "55d0a6feab0332116d74b253",
        "status": "available",
        "sequence": 0,
        "body_original": "So this is it.",
        "__v": 0,
        "body_translated": "Así que esto es."
      }
    ];
      $scope.test = $filter('orderBy')($scope.segments, 'sequence');
      console.log($scope.test);
    }]);
  </script>

</body>

Answer №2

A simple solution is to sort the array directly, which eliminates the need for using orderBy in the view. However, this approach may remove some of the dynamic binding features if new elements are added:

$scope.items.sort(function(x, y) {
    return x.position - y.position;
});

Answer №3

It was pointed out by tymeJV that the API call is asynchronous, causing crucial data to be absent and making it difficult to provide a complete answer.

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

Expo + tRPC: Oops! Looks like the application context couldn't be retrieved. Don't forget to wrap your App inside the `withTRPC` HoC for

I'm currently working on a straightforward tRPC server setup: // server.ts import { initTRPC } from "@trpc/server"; import { z } from "zod"; const t = initTRPC.create(); export const appRouter = t.router({ greeting: t.procedu ...

Exploring the World of Infinite Scrolling with React.js and Material_ui

I am currently working on a project using react.js As part of this project, I need to implement a board with infinite scroll similar to Facebook I have a specific question regarding this implementation. When scrolling the board and loading more posts li ...

Enhance a collection by incorporating methods to the result of an angular resource query

After executing a query, I am left with an array from the resource: .factory('Books', function($resource){ var Books = $resource('/authors/:authorId/books'); return Books; }) I was wondering if there is a way to incorporate pr ...

Working with double quotes within variable in JavaScript

I am currently working on dynamically creating HTML tags using JavaScript. Please take a look at the code snippet below: function getPhotosSuccess(data) { if (data.d.results.length > 0) { var response = data.d.results; var innerht ...

Change the data returned by Ajax

After making an ajax request, my table gets populated with data from my array. The return is as expected, but now I want to modify this data before displaying it to the user. Whether this modification happens before or after the data is placed in the table ...

jQuery performs perfectly in Chrome but encounters issues in IE9/IE8 and other older versions of Internet

I've implemented this lengthy jQuery script to enable dynamic dropdown loading and updating when selections are changed. However, I'm facing issues in Internet Explorer where the script loads the dropdowns initially but doesn't trigger oncha ...

Determine whether a response is not received within 8 seconds

One of the methods in my Angular component is responsible for returning data Here is a snippet of that method getRecognitionById() { this.loaderService.show(null, true); forkJoin( this.vendorWebApiService.getRecognitionById(this.executiveCh ...

Taking out the z-index from the transition code

Is there a way to restructure the code without needing to use z-index for the transition? Without z-index: https://jsfiddle.net/Legcb42d/ .container1 { position: relative; width: 100%; height: 100%; } .container1.slide { height: auto; min-heigh ...

Duplicate text content from a mirrored textarea and save to clipboard

I came across some code snippets here that are perfect for a tool I'm currently developing. The codes help in copying the value of the previous textarea to the clipboard, but it doesn't work as expected when dealing with cloned textareas. Any sug ...

Tips for efficiently printing invoices on specific paper: Print a maximum of 20 items per sheet, and if it exceeds this limit, continue onto the next page. Ensure the total amount is

$(document).ready(function(){ var j = 23; for (var i = 0; i < j+11; i++) { if (i != 0 && i % 11 == 0) { $("#printSection div").append("<?php echo '<tr><td>fff</td></tr>'; ?>"); ...

It is important to ensure that the user returned by the onAuthStateChanged function in

server admin.auth().createCustomToken(uuid) .then((customToken) => { admin.auth().createUser({ email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed989e889fad88958c809d8188c38e8280">[email protected] ...

Is there a problem with the way divs are being displayed when using jQuery to show the first 12 elements with the class "hide-show"?

I am encountering a problem with displaying data using the jQuery slice() and show() methods to reveal dynamically generated divs from a PHP function. The code is as follows: <style> .hide-show { display :none; } </style> <div class="c ...

How to retrieve the value of a nested checkbox in Angular using dynamic methods

I successfully developed dynamic nested checkboxes in Angular and now I am looking to retrieve the values of the selected checkboxes. However, I encountered an issue with the JSON structure needed to implement this functionality. https://i.stack.imgur.com ...

Exploring the benefits of leveraging Express with SSL security features

I recently acquired a Comodo SSL certificate for setting up an SSL server with express. The certificates I have include: AddTrustExternalCARoot.crt COMODORSAAddTrustCA.crt COMODORSADomainValidationSecureServerCA.crt mysite.com.key mysite.com.csr mysite_co ...

jQuery plugin stops functioning properly following the use of the jQuery display block method

In my project, I am exploring the use of divs as tabs with jQuery. Within these divs, I also want to incorporate another jQuery plugin. Currently, I have manually created these div tabs using jQuery and set the default style for second and subsequent divs ...

Differentiate between chrome and chromium with the help of Javascript programming

Can we differentiate between Google Chrome and the open-source Chromium browser using JavaScript? It appears that the navigator.userAgent property is the same in both browsers. ...

Jquery issue: Lightbox unexpectedly closing by itself :(

Help needed: My light box is closing automatically within seconds. $(document).ready(function(){ $('.lightbox').click(function(){ $('.backdrop, .box').animate({'opacity':'.50'}, 300, 'linear'); ...

Executing a function by clicking on an element with the `ng-click` directive within a Bootstrap modal

I'm working on an app that allows users to submit posts for review. When a user clicks the add post button, I have a Bootstrap modal pop up to confirm their choice. Within this modal, there is a "confirm" button that should trigger a function. Strang ...

While validating in my Angular application, I encountered an error stating that no index signature with a parameter of type 'string' was found on type 'AbstractControl[]'

While trying to validate my Angular application, I encountered the following error: src/app/register/register.component.ts:45:39 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used ...

How to make an HTTPS REST API request in Node.js with JSON body payload

Currently, I am attempting to make a secure HTTPS REST request in Node.js by utilizing the following code: var querystring = require('querystring'); var https = require('https'); var postData = { 'Value1' : 'abc1&ap ...