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

JS Implementation of the Coin Change Algorithm

I've been grappling with this algorithm for the past few days, but unfortunately I haven't been able to come up with a successful solution yet. The available solutions seem to be too advanced for my current level of understanding. This problem mu ...

Are there any negatives to turning off create-react-app's SKIP_PREFLIGHT_CHECK option?

After setting up my create-react-app project, I added eslint as a dev dependency. My reasons for doing this include: 1) Running eslint as a pre-commit check using husky and lint-staged 2) Extending CRA's eslint with airbnb and prettier lint configs ...

The SDK generated by AWS API Gateway does not include the JavaScript client file

After setting up my API with the AWS Api Gateway Service, I am now looking to integrate the javascript SDK into a basic webpage. The provided instructions for using the javascript SDK can be found here. However, they mention importing a js file named apig ...

Issue TS8011 in Angular 6 is related to the restriction on using type arguments only in files with the .ts extension

I have a project in Angular 6 where I need to integrate a JS library. This library is confidential, so I can't disclose its details. The problem I'm facing is that the TypeScript compiler seems to misinterpret characters like <<24>>, ...

Encountered an issue during my initial AJAX call

Hello everyone, I am currently attempting to use AJAX to send a request with a button trigger and display the response HTML file in a span area. However, I am encountering some issues and need help troubleshooting. Here is my code snippet: //ajax.php < ...

Combine multiple key values from an array of objects into a single array

I have a set of key and value pairs that I need to filter based on whether the values are in an array or not, and then combine them into a single array. const holiday_expenses = { food: [{name: "abc", place: "xyz"}], travel: [{name: ...

Accessing React Context globally using the useContext hook

I'm feeling a bit puzzled about how the useContext hook is intended to function in a "global" state context. Let's take a look at my App.js: import React from 'react'; import Login from './Components/auth/Login'; import &apos ...

increase the count by one every second using setInterval

I need my sHand to increase by 6 every second, but currently it only increases once. When I try something like this.sHand++, it works fine and increases by 1 degree per second. However, I want it to increase by 6 instead of 1. Any solutions? data:{ ...

Froala Editor: Innovative external toolbar that pops up when the button is clicked

In our project, we are implementing the latest version of Froala and aim to configure it so that the toolbar is activated by a separate external button, similar to Gmail where the editor initially does not display a toolbar. I attempted to modify the &apo ...

Error: pos variable is not defined

I encountered a TypeError: pos is undefined while running the code below. $(document).ready(function() { var s = $("#col-scroll"); var pos = s.position(); $(window).scroll(function() { var windowpos = $(window).scrol ...

Tips for troubleshooting ImageArray loading issues in AngularJS

Having some trouble learning Angular and getting stuck with this Image array. Can someone please help me understand what's wrong with my code and how to fix it? FilterAndImages.html <!DOCTYPE html> <html ng-app="store"> <head> < ...

Troubleshooting: Issue with running npm start | React app not loading

npm start command seems to be stuck at this particular point - The application is failing to load because of this issue. Here is the content of package.json file - { "name": "reacttest", "version": "0.1.0", & ...

Navigating the browser view across an extensive HTML page without relying on scrollbars

I have a large HTML page (approximately 7000x5000) and I need to be able to move the user's view around with JavaScript. Disabling the ability for the user to scroll by hiding the browser scrollbars using overflow:hidden on the HTML element is easy. ...

transferring information to a different application module (or page) through a double-click feature in AngularJS

Within my angularjs application, I am faced with a challenge involving two pages. The first page retrieves data from a database and displays it in a table. Upon double-clicking on a row, the user is directed to another page where more detailed informatio ...

After installing grunt, the Gruntfile cannot be located. How can this issue be resolved?

After installing grunt, I encountered a problem. Despite trying some commands suggested on stackoverflow in this How to install grunt and how to build script with it, running the grunt command still shows the same result. What steps should I take next?ht ...

Testing with mount in React Enzyme, the setState method does not function correctly

I've been experimenting with testing this code block in my React App using Jest and Enzyme: openDeleteUserModal = ({ row }: { row: IUser | null }): any => ( event: React.SyntheticEvent ): void => { if (event) event.preventDefault(); ...

Using Node.js to invoke an identifier loop

Having some trouble with this loop. Should I include variable c in the loop as well? Let me provide some context: there is a table and child(i) changes for every row. The SelectorT receives a sentence structured like this: Now\nIs\n09:00\n4 ...

What is the best method for displaying the date/time with timezone in AngularJS?

While utilizing the AngularJS filter date, I have incorporated the following code snippet: var date = new Date("09 apr 2015 12:00:50 UT"); $filter('date')(date, "dd MMM yyyy hh:mm:ss a Z"); The current output is: 09 Apr 2015 08:19:04 PM + ...

The minimum and maximum limits of the Ionic datepicker do not function properly when selecting the month and day

Recently, I have been experimenting with the Ionic 2 datepicker. While the datepicker itself works perfectly fine, I've run into some issues when trying to set the min and max properties. <ion-datetime displayFormat="DD-MM-YYYY" [min]="event.date ...

Storing property data outside of the render method in ReactJS is key for efficient

I have encountered an issue while attempting to map data outside of the render method in my function and return it within the render. The mapping error is causing confusion as I am uncertain about its underlying cause. Below is the function responsible fo ...