arrange list in Angular.js

Currently, I am attempting to sort an array using Angular JS with the orderBy function. However, I am experiencing difficulties sorting it based on a specific key.

Below is the code snippet:


var app = angular.module('sortModule', [])
app.controller('MainController', function($scope,$filter){    
    $scope.languages = [ 
        { name: 'English', image: '/images/english.png',key:2 },
        { name: 'Hindi', image: '/images/hindi.png',key:3 },
        { name: 'English', image: '/images/english.png',key:2},
        { name: 'Telugu', image: '/images/telugu.png',key:1 }
    ];        

    var newLanguages = []
    newLanguages = angular.copy($scope.languages);  
    function sortImages() { 
        $scope.languages = []
        $scope.keys = []        
        for(language in newLanguages) {
            $scope.keys.push(newLanguages[language])
        }
        $filter('orderBy')($scope.keys, 'key')
        console.log(JSON.stringify($scope.keys))
    }

sortImages();

});

Access Fiddle here

I aim to achieve sorting based on the "key" field, where Telugu should be prioritized first, followed by English, and lastly Hindi.

Answer ā„–1

To achieve this, you must have:

$scope.items = $filter('orderBy')($scope.keys, 'key', false) 

The orderBy filter generates a new array instead of modifying the original one.

Check out the updated demo: http://jsfiddle.net/exampledemo/123/

Answer ā„–2

Modify the HTML markup by removing the OrderBy to display an unordered list:

<div ng-app="sortModule" class="nav">
<div ng-controller="MainController">


    <button ng-click="sort()">Sort  
    </button>
    <div></div>
    <div >        
        <ul>
            <li ng-repeat="lang in languages">
               <span>{{lang.name}}</span>
            </li>
        </ul>
    </div>
    </div>
</div>

Now, use the sort button to rearrange the list.

var app = angular.module('sortModule', [])
app.controller('MainController', function($scope,$filter){    
    $scope.languages = [ 
            { name: 'English', image: '/images/english.png',key:2 },
            { name: 'Hindi', image: '/images/hindi.png',key:3 },
        { name: 'English', image: '/images/english.png',key:2},
        { name: 'Telugu', image: '/images/telugu.png',key:1 }];        

    var newLanguages = []
    newLanguages = angular.copy($scope.languages);  
    $scope.sort = function(){ 
            $scope.languages = []
        $scope.keys = []        
            for(language in newLanguages) {
                $scope.keys.push(newLanguages[language])
        }
        $scope.keys = $filter('orderBy')($scope.keys, 'key', false);
        $scope.languages = $scope.keys;
        console.log(JSON.stringify($scope.keys))
    }
});

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 process for setting the version in a serverless project?

Recently I downgraded the serverless to version 1.38.0 using the command npm install -g <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="047761767261766861777744352a373c2a34">[email protected]</a>. This triggered in ...

Tips for extracting CSS data with Selenium webdriver's executescript function

Just starting to learn Javascript in a Node environment... I'm trying to use the code snippet below to extract CSS values for a specific web element, but I'm having trouble parsing it in JavaScript. driver.executeScript(script, ele).then(p ...

In Lightning Web Components, there seems to be an issue with the splice method not functioning correctly when used with an @api

When checking the console, I noticed that this.unselectedPlayerList.length is not displayed until after using the splice method. This has raised some doubts in my mind about how the splice method works. export default class MakeYourTeamChild extends Ligh ...

What is the best way to define coordinates or set margins for the autoTable component in jsPdf when using React js?

While working with the jsPdf library to create a PDF in React, I am encountering an issue where I am unable to set margins for the autoTable when there are multiple tables on a single page. Below is the code snippet: import React from "react"; ...

Ways to eliminate brackets from a string

Currently, I am working on a challenge involving replacing strings using a function that accepts a string and an object of values. This task involves a two-part algorithm: Replacing values within the string that are enclosed in braces. If the value is wi ...

Adding a div beside an input element - step by step guide

When creating an input field in my code, I followed these steps: var inputVal = document.createElement("input"); inputVal.setAttribute("type", "checkbox"); inputChek.onchange = select; inputChek.setAttribute("value", title); //inputChek.after(sortDiv); ...

Is it possible to retain the model value when clicking the back button in the browser using AngularJS?

I'm new to AngularJS and I have a dropdown along with a link. What I want is for AngularJS to remember the selected value in the dropdown even after clicking the link, and then going back using the browser's back button. Currently, when I click t ...

Text area featuring unique border design, with border color change upon focus?

Currently, I have a text area with borders that are designed in a unique way. However, I am looking to change the border color when the user focuses on the text area. Do you have any suggestions on how I can achieve this effect without affecting the curre ...

Numeric value along with two characters following the decimal place

Imagine I have this number: 25297710.1088 My goal is to add spaces between the groups of digits and keep only two decimal places, like this: 25 297 710.10 I tried using the following code snippet: $(td).text().reverse().replace(/((?:\d{2})&bso ...

deployJava.js injects a new <embed> element into the header section of the webpage

I've ran into an issue with the Java applets on my website. I included the deployJava.js load tag in the head section of the page, but when I look at the resulting HTML in Chrome debugger, this script seems to be breaking my head content and starting ...

Adjusting image dynamically based on conditions

I need to dynamically display images on my HTML based on specific conditions using TypeScript. In my TypeScript file: styleArray = ["Solitary", "Visual","Auditory","Logical","Physical","Social","Verbal",]; constructor(){ for (var i = 0; this.sty ...

Error encountered: The JSONP request to https://admin.typeform.com/app/embed/ID?jsoncallback=? was unsuccessful

I encountered an issue with the following error message: Error: JSONP request to https://admin.typeform.com/app/embed/id?jsoncallback=? Failed while trying to integrate a typeform into my next.js application. To embed the form, I am utilizing the react-ty ...

Is it possible for me to utilize jquery and AJAX to invoke a cgi-bin script, and then incorporate a message event to manage Server Sent Event?

I have a cgi-bin program that runs for a long time (3-15 minutes) and I am looking to invoke it using AJAX. While the program is running, I want to receive Server Sent Event data from it and display it on my web page. It's like having a progress monit ...

Aggregate information from an array containing multiple nested arrays

With regards to marking this as answered by another question, please take note that this is not a flat array but an array of arrays. Additionally, the numbers provided are just examples for visual representation. I am attempting to iterate through an arra ...

Can I assign a custom form id before manually triggering submission using AJAX?

I have developed an interesting code snippet that uses AJAX to submit a form only if the form has an ID attached to it. $(document).delegate('form', 'submit', function(event) { var $form = $(this); var id = $form.attr('id& ...

JavaScript can be used to create dynamic frames within a

Can anyone help identify the issue in my code? frame 1 <script type="text/javascript"> var Clicks = 0 ; function AddClick(){ Clicks = Clicks + 1; document.getElementById('CountedClicks').innerHTML = Clicks ; } localStorage.setItem(' ...

Guide to displaying radio button value when updating a record

When updating a record in Node.js, I encounter an issue where the values for text input fields are rendered correctly, but the values for radio buttons and textarea in the update form do not appear. Can someone please advise on how to implement this? I am ...

Best practices for managing a Media Stream in Node.js

One of the latest and most exciting features in modern browsers is HTMLMediaElement.captureStream(), which has recently been released in Chrome. Having grasped how it functions on the client side - allowing you to redirect the stream to other HTMLMediaEle ...

Enhance the appearance of Ionic popups

Can someone help me with resizing a pop up? I've been struggling to get it right. This is the popup template in question: <ion-view> <ion-content scroll="false" class=""> test </ion-content> < ...

Preventing text from wrapping in a TypeScript-generated form: Tips and tricks

Iā€™m currently working on a ReactJS project and my objective is simple: I want all three <FormItem> components to be displayed in a single line without wrapping. However, I am facing the following output: https://i.stack.imgur.com/mxiIE.png Within ...