Unable to sort nested JSON data in ngTable

I have successfully built an angularjs application using ngTable, however, I am facing an issue with sorting. The JSON structure is nested but the values are appearing correctly in the table.

If anyone has a solution to this problem, please let me know.

Here is my code:

JSFiddle

html

<div ng-controller="IndexCtrl">
    <table border="1" ng-table="mytable">
         <tbody ng-repeat="peop in peoples">
        <tr ng-repeat="people in peop">
            <td sortable="'id'" data-title="'Id'">{{people.id}}</td>
            <td sortable="'desig'" data-title="'Desig'">{{people.desig}}</td>
            <td sortable="'name'" data-title="'Name'">{{people.name}}</td>
            <td sortable="'place'" data-title="'Place'">{{people.place}}</td>
        </tr>
        </tbody>
    </table>
</div>

script

var app = angular.module('app', ['ngTable']);
    
app.controller('IndexCtrl', function ($scope, $filter, ngTableParams) {
  $scope.peoples = {
    "ime123": [{"id": 145, 
                "desig": "doctor",
                "name": "Manu",
                "place": "ABCD"
               }],
    "ime148": [{"id": 148,
                "desig": "engineer",
                "name": "John",
                "place": "POLK"
               },
               {
                "id": 150,
                "desig": "scientist",
                "name": "Mary",
                "place": "USE"
               }]
  };    
        $scope.mytable = new ngTableParams({
        sorting: {
            name: 'desc'
        }
    }, {
        getData: function($defer, params) {
        $scope.peoples = $filter('orderBy')( $scope.peoples, params.orderBy());
        $defer.resolve( $scope.peoples);
        }
    });
});

Answer №1

If you're struggling with handling nested arrays in ngtable, consider simplifying your array structure and allowing the directive to handle grouping.

HTML

<table border="1" ng-table="mytable">
        <tbody ng-repeat="peop in $groups">
            <tr ng-repeat="people in peop.data">
                <td sortable="id" data-title="'Id'">{{people.id}}</td>
                <td sortable="desig" data-title="'Desig'">{{people.desig}}</td>
                <td sortable="name" data-title="'Name'">{{people.name}}</td>
                <td sortable="place" data-title="'Place'">{{people.place}}</td>
            </tr>
        </tbody>
    </table>

Controller

$scope.mytable = new ngTableParams({
        page: 1,           
        count: 10,          
        sorting: {
            name: 'desc'
        }
    }, {
        total: peoples.length,
        groupBy:'group',
        getData: function ($defer, params) {
            peoples = $filter('orderBy')(peoples, params.orderBy());
            $defer.resolve(peoples);
        }
    });

Data

var peoples = [{
        "id": 145,
            "desig": "doctor",
            "name": "Manu",
            "place": "ABCD",
            "group": "ime123"  
    }, {
        "id": 148,
            "desig": "engineer",
            "name": "John",
            "place": "POLK",
            "group": "ime148" 
    }, {
        "id": 150,
            "desig": "scientist",
            "name": "Mary",
            "place": "USE",
            "group": "ime148"  
    }];

You can view a demo on jsfiddle. Keep in mind that the default desc sorting may not be functioning correctly yet (version 0.3.1).

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 most efficient way to use the $slice operator on a highly nested array in mongoose

I am currently working on slicing a deeply nested array. To illustrate, consider the following structure. I aim to slice this array for pagination purposes. {messages: [{ message: { members: [ {example: object, blah: blah}, {example2: object2, blah2: blah ...

Module not found (Error: Module not found for './models/campground')

Here is the code snippet I am working with: var express = require("express"), app = express(), bodyParser = require("body-parser"), mongoose = require("mongoose"), Campground = require("./models/campground"), Comment = require("./mode ...

Utilize Angular data binding to assign a class

Within my array, there is an element that holds a value of true or false. This value guides the display logic in this example: <div ng-show="{{ item.isDirectory }}"> Moreover, I seek to implement a similar condition for adding a CSS class to the ...

Switching icon with jQuery upon clicking

I'm just starting to learn jQuery and I'm working on changing the font icon class when clicked to display a drop down. Right now, it changes the icon and drops down the content as expected. However, I'm facing an issue where I want the icon ...

Dealing with JSON object as a string in API using Laravel with PHP

I have a Python API that generates a JSON object with data on staff behavior. The response looks like this: { "Text":{ "0":"Very unfriendly staff at reception: not responding to needs and giving wrong information.", "1":"The staff are polit ...

Merging two arrays with lodash for a seamless union

Here are two arrays I'm working with: arr1 = [ { "key1": "Value1" }, { "key2": "Value2" }, { "key3": "Test3" }, { ...

Sending the format of the display value to an Angular component

Looking for a way to pass display value formatting to an Angular component. Here are a couple of examples: format="'(utc, offset) location (tz)'" === '(UTC -04:00) New York (EDT)' or format="'(tz, offset) location'" === &a ...

What is the best way to design a grid with various squares in React Native?

Here's the design I aim to achieve: I am looking to implement the above layout in react native and ensure it is responsive on all screen sizes. I attempted using flexbox but couldn't figure out how to make the boxes square shaped. The code provi ...

Pass the input value through ajax without utilizing the val() function

Here is my scenario: I have multiple input fields: <label class="minilabel">Field1</label><input type="text"> ... <label class="minilabel">FieldN </label><input type="text"> I need to extract the value of each input f ...

Utilizing JQ to apply various filters within nested arrays

In my JSON data, I have nested arrays for each item I need to collect. Here is a simplified version: [ [ { "Item":"FIRST", "items":[ { "firstitem1":"Item 1", ...

Utilizing Flow JS to import user data from a CSV file

Looking to incorporate file upload feature in my AngularJS application. The requirement is to allow users to upload only CSV/XSL files with a file size restriction of 100KB. The data from the uploaded file should be stored in the local storage of the bro ...

The ng-model failed to display the updated value until a click was made somewhere on the page

I am struggling with displaying the correct value of an ngModel variable defined in my controller. Despite changing to the correct value in the console, it doesn't update on the page until I click somewhere else or hit the update button again. Here&a ...

Having difficulty rearranging choices within an optgroup

This is a dropdown https://i.sstatic.net/Rk5yL.png <select id="officer-id" placeholder="Choose an officer"> <option selected="selected" >----</option> <optgroup id="pt1" label="To be reviewed"> ...

Is it possible for jQuery to fail within an object method?

Consider this scenario: function Schedule (foo) { this.foo = foo; this.bar = function() { $.ajax({ url: '/something/', method: "GET", dataType: "JSON" }).done (function(data){ ...

webdriver: object not found (successfully executes in IDE)

Seeking assistance! I have an input element (shown below) that I am struggling to locate or insert text into. It functions properly in my IDE but not when running my code in Java. The code snippet is as follows: driver.findElement(By.id("searchjobbynam ...

What steps do I need to follow in order to incorporate and utilize an npm package within my Astro component

I have been working on integrating KeenSlider into my project by installing it from npm. However, I am encountering an error message that says Uncaught ReferenceError: KeenSlider is not defined whenever I try to use the package in my Astro component. Belo ...

Experiencing trouble with calculating the total value of an array of objects due to NaN errors

I've been working on developing this web application in VUE.js, but I'm facing an issue with a specific function where I am attempting to sum the values of each object within an array. This is resulting in a NaN (Not a Number) error. Let's t ...

Is there a bug in Safari 8.0 related to jQuery and backslashes?

I am using Mac OS 10.10 Yosemite and Safari 8.0. Attempting to read an XML (RSS) file: <content:encoded>bla bla bla</content:encoded> The Javascript Ajax method I am using is: description:$(valeur).find('content\\:encoded&apo ...

The tab component is failing to load due to an issue with the Bootstrap tab

I've created a page displaying different locations with two tabs - one for Google Maps and another for weather. For example, take a look at this location: The issue I'm facing is that when switching between the tabs, they don't load fully. ...

Real-time data feeds straight from JSON

Currently, I have a JSON file that is generated dynamically and it contains match information along with a unique id. This JSON data is categorized into live, upcoming, and recent arrays. Being new to Javascript, I am unsure about the best approach to crea ...