How to sort objects by keys in AngularJS

Currently, I am working on building a sorting list using AngularJS. The goal is to have the data updated in the DOM dynamically when a user clicks on the name of a value. I am attempting to order the values by categories such as Bracelets, Charms, Earrings, and so on. Below is an example of how I could achieve this:

$scope.sortOptions = ['Bracelets','Charms', 'Earrings', ...]; // providing sorting options
$scope.sort = 'Bracelets'; // setting a default sortby item

$scope.active = function(x) {
    return x === $scope.sort ? 'active' : '';
};

$scope.setSort = function(type){ 
    $scope.sort = type.toLowerCase();
}; 

However, this method only works for a single object. In reality, I will need to handle multiple objects retrieved from the server.

Below is an example of my Category object structure:

{
    "Pandora": {
        "id": "1",
        "s1": {
            "d1": "Bracelets",
            "d2": "Charms",
            "d3": "Earrings",
            "d4": "Jewelry",
            "d5": "Necklaces",
            "d6": "Pendants",
            "d7": "Rings"
        }
    }
}

I have come across limitations with using AngularJS orderby without an array of objects, as discussed on StackOverFlow. To work around this, in my controller, I initialize $scope.catData = []; and then populate it with data fetched from the server through a factory.

dataFactory.getCat().then(function(res){
  $scope.catData = res.data;
});

Here is a snippet of what my HTML code looks like:

<li ng-repeat="(key, value) in catData">
   <a href="#" data-id='{{value.id}}' class="anchor">{{key}}</a>
   <ul class="sub" ng-class="{true: 'activeSlideF'}[value.id == 1]" >
      <span ng-repeat="hi in value.s1 | orderBy:'hi':true">
         <li>
            <a href="#"><i class="fa fa-arrow-right"></i>{{hi}}</a>
         </li>
      </span>     
   </ul>
</li>

I suspect that when I assign $scope.catData = res.data, existing data might be overwritten. While a quick solution could be $scope.catData = [res.data], I am not sure if this is the ideal approach. Any insights or suggestions would be greatly appreciated!

Thank you for your assistance!

Answer №1

To update a scope variable displayed in the DOM, you can utilize ng-click and ng-model.

Check out this example along with a JSFiddle:

HTML

<div id="example" ng-app="myApp">
    <div ng-controller="exampleController">
        <h2 ng-model="message">{{message}}</h2>
        <ul ng-repeat="item in items">
            <li ng-repeat="value in item.data" ng-click="updateValue(value)"><button ng-value="{{ value }}">{{ value }}</button></li>
        </ul>
    </div>
</div>

JS

var app = angular.module('myApp', []);

var myData = "...Insert your JSON data here...";

app.controller('exampleController', ['$scope',
    function($scope) {
        $scope.message = "Click to update the message:";
        $scope.items = myData;
        $scope.updateValue = function(val) {
            $scope.message = val;
        }
    }
]);

JSFiddle

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

"Unspecified error in Angular" encountered when implementing Mobile Angular UI in conjunction with Angularfire

I am currently working on developing a mobile app using Mobile Angular UI and integrating it with a Firebase database. However, I keep encountering an error when trying to include Firebase: Uncaught ReferenceError: angular is not defined at angularfire.m ...

Having trouble executing an npm script - getting an error message that reads "Error: spawn node_modules/webpack/bin/webpack.js EACCES"

After installing and configuring Linux Mint, I encountered an error when trying to run my project with the npm run dev command. The error message "spawn node_modules / webpack / bin / webpack.js EACCES" keeps appearing. I have attempted various methods fo ...

waiting for udp response in node.js using express

Currently, I am diving into the world of node.js programming and have encountered a challenge. While working with express, I came across an issue. When a POST request is made, it triggers a radius authentication process over UDP using the dgram module. Ho ...

Incorporate audio playback on image click using JavaScript, with the feature to automatically pause the playback if multiple images are playing simultaneously

<img class="cl" src="photo/198.jpg"/></br> <audio class="cs" controls> <source src="audio/198 banu nagamothu.mp3" type="audio/mpeg"> </audio> I prefer not to have audio controls initially, but when the image i ...

Storing the indices of duplicate values in an array using iOS Swift

Imagine having an array like this: let dates = ["01/02/16", "02/02/16", "03/02/16", "01/02/16", "02/02/16"] The goal is to store each unique String date as a key in a dictionary. For duplicate keys, we want to store the indices where they occur in an arr ...

The result obtained from response.download() is saved as a blob that may contain undefined elements

I am in the process of developing a client-server certificate generator. In terms of the Backend, I have set up two endpoints: / This endpoint receives a JSON containing extracted data from inputs, sanitizes them, and determines if they are valid or not ...

What are the reasons for validation failure when it is moved into a method?

I am currently in the process of developing a validation function in JavaScript. However, when I extracted the logic into a private method, my validation started failing and I can't seem to figure out why. Here is my HTML definition: <input type= ...

Troubles encountered when populating the array within a Vue component

I am experiencing an issue with my ProductCard component where the addItem method is not successfully adding a new item to the array. <template> <div class="card"> <div v-for="item in TodoItems" :key="item.id ...

Tips for adding your artistic touch to photos

I'm currently facing a challenge in creating a chart that overlaps an image. The bars and text on the chart are displaying perfectly when I remove the background image. However, I'm struggling to get the bars and text to appear on top of the imag ...

Shifting hues of dots within a grid according to the passing of time

As a newcomer to the world of coding, I have conceptualized an idea for a visually appealing clock. My goal is to visually represent the passage of time throughout the day. To achieve this, I have devised a grid system where each dot on the grid represents ...

Basic AngularJS application, however I am receiving {{this is supposed to be the information}}

Building an angularjs app I have set up an asp.net mvc4 application and integrated the angularjs package using nuget. The Layout.cshtml file has been updated to look like this: <!DOCTYPE html> <html ng-app="myApp"> <head> <meta ...

Enhance dynamically generated HTML using jQuery Mobile

Using jQuery Mobile version 1.2.0 I am dynamically generating HTML using JavaScript ($(selector).html(content)), adding it to the DOM, and then displaying it ($.mobile.changePage()). After that, I make an AJAX call, retrieve some data, and re-generate th ...

Tips for invoking an Android function from an AngularJS directive?

I am facing an issue with my HTML that uses an AngularJS directive. This HTML file is being used in an Android WebView, and I want to be able to call an Android method from this directive (Learn how to call Android method from JS here). Below is the code ...

Tips for effectively engaging with a Component's aggregationUnleash the full potential of

After configuring an aggregation for my Component, here is what it looks like: aggregations : { busyDialog : { type: "sap.m.BusyDialog", multiple: false } } The aggregation is named ...

Navigating to a particular page in ReactJS using a unique JSON identifier

I need to navigate to a particular page and display a specific JSON Object. If the JSON Object contains ID: 1, then it should redirect to localhost:300/users/1 and display the data of ID 1. I have also linked another JSON file that contains user addresses, ...

Failed to convert the value "hello" to an ObjectId (string type) for the _id path in the product model

i am currently using node, express, and mongoose with a local mongodb database. all of my routes are functioning correctly except for the last one /hello, which is giving me this error: { "stringValue": "\"hello\"&qu ...

Using 'if' conditions in Reactjs: A step-by-step guide

Working with Reactjs in the nextjs framework, I have received user data that includes the "category name (cat_name)" selected by the user. Now, I need to display that category in a dropdown menu. How can I achieve this? The current code snippet showcases ...

What is the best location to place the code responsible for fetching data with NSURLRequest?

As I venture into the world of developing my first iPhone app, one that fetches JSON data and displays it in UITableView, I find myself pondering a crucial question. Where is the ideal spot in my code to place the NSURLRequest? In my quest for answers, I& ...

Python: Best practices for handling multiple users efficiently in your application

After compiling a list of user IDs and their friend IDs, the task at hand is to create a program that sends messages to each user's friends. The most efficient approach would involve storing this information in a single file using JSON format: {&apos ...

Encountering an unexpected token error while trying to attach a variable to a child

There are two directives in my code, with one being the child of the other: .directive("mbVideo", function(mbFileReader){ return { restrict : "EA", scope: { "videoModel" : '=model' }, templateUrl: 'mbUpload/mbVid ...