The sorting functionality in Angular.js using the orderBy directive seems to be malfunctioning as it is not

Within this code snippet, @Model.jsonString represents a string.

@model WebApplication1.Models.Car
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<html>

...

<body ng-app="myModule">
<div ng-controller="myContoller" ng-init="init(@Model.jsonString)">

...

</div>


</body>




</html>

The script.js code segment is shown below:

/// <reference path="angular.js" />
var app = angular
    .module("myModule", [])
    .controller("myContoller",
        function ($scope) {

            $scope.init = function(jsonString) {
                //This function acts as a private constructor for the controller

                $scope.cars = jsonString;


            };
            $scope.sortColumn = "Name";
        });

An issue has been encountered when attempting to sort columns using orderBy:sortColumn. Any insights or suggestions would be highly appreciated. Thank you.

Answer №1

When creating select box value names, ensure they match the array property name. Also, remove the plus icon and use - only if ordering items in descending order.

angular
.module("myModule", [])
.controller("myContoller", function($scope) {
$scope.init = function(jsonString) {
//This function acts as a private constructor for the controller
$scope.cars = [  
         {  
            'mileage':'16',
            'name':'asss',
            'model':'sst',
            ' engine':'aagaa',
            'color':'yellow'
         },
         {  
            'mileage':'14',
            'name':'sss',
            'model':'sdt',
            ' engine':'avaaa',
            'color':'red'
         },
         {  
            'mileage':'12',
            'name':'dsss',
            'model':'sgt',
            ' engine':'aaaaa',
            'color':'blue'
         }
      ];
};
    $scope.init ()
$scope.sortColumn = "Name";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myModule">
<div ng-controller="myContoller" 
 >

    OrderBy : <select ng-model="sortColumn">
        <option value="mileage">Mileage Asc</option>
        <option value="name">Name Asc</option>
        <option value="model">Model Asc</option>
        <option value="engine">Engine Asc</option>
        <option value="color">Color Asc</option>

    </select>
    <table class="table">
        <thead >

            <tr class="th">
                <th>Mileage</th>
                <th>Name</th>
                <th>Model</th>
                <th>Engine</th>
                <th>Color</th>
            </tr>
        </thead>
        <tbody>

            <tr ng-repeat="car in cars | orderBy:sortColumn">
                <td>{{car.mileage}}</td>
                <td>{{car.name}}</td>
                <td>{{car.model}}</td>
                <td>{{car.engine}}</td>
                <td>{{car.color}}</td>

            </tr>

        </tbody>
    </table>
</div> 
</body>

Answer №2

The option values are in uppercase while the object properties are in lowercase.

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

Unable to locate the <router-view> component within VueRouter

I recently completed a project using Vue.js 3.2.13 and Vue-Router 4.0.14. Despite my efforts to ensure everything was set up correctly, I encountered an error in the browser that said "[Vue warn]: Failed to resolve component: router-view". The specific lin ...

The value entered for creating a payment method is invalid: the card must be in the form of an object

I am in the process of setting up a payment method using the Next.js library from Stripe. Here is the code snippet: import React, { FunctionComponent } from 'react'; import type { DisplaySettingsProps } from '@company/frontoffice/types' ...

Tips for updating Angular HTML with data received from Socket.IO

I am currently working on a socket program that is listening and providing log data. The socket is sending the correct data as I can see it in the console. Below is a snippet of my code: export class RoboLogComponent implements OnInit { dataToShow:any @V ...

Setting up TypeScript in an Angular 2 project and integrating Facebook login

Currently, I am in the process of familiarizing myself with Angular 2 and typescript. Although things have been going smoothly so far, I have hit a roadblock while attempting to implement a Facebook login message. In my search for a solution, I stumbled up ...

What causes the disparity in the functionality of getServerSideProps between index.js and [id].js in NextJS?

Exploring NextJS and React as part of my e-commerce site development journey has been exciting. However, I encountered a roadblock when trying to connect to an external database that requires real-time updates, making getStaticProps unsuitable for my needs ...

When the scope variable is updated in AngularJS, the Digest process does not automatically get triggered

Currently, I am utilizing AngularJS along with angularFire to display a list of my tasks: <ul ng-repeat="tool in tools"> <li>{{tool.name}} {{ tool.description}}</li> </ul> var toolRef = new Firebase(dbRef + "/tools/" + toolId) ...

Which specific file name patterns does npm publish consistently exclude?

When using the npm publish command, the documentation mentions that certain files will not be included in the package unless explicitly added to the "files" list in package.json or un-ignored with a specific rule. What exactly are these "certain patterns"? ...

Guide on implementing iterative data path in v-for loop using Vue

I'm just starting out with Vue and I want to use image file names like "room1.jpg", "room2.jpg", "room3.jpg" in a loop Below is my code, where the second line seems to be causing an issue <div v-for="(p,i) in products" :key="i"> <img src ...

The autoIncrement feature is causing a syntax error at or near "SERIAL"

Encountering a build error : Unable to start server due to the following SequelizeDatabaseError: syntax error at or near "SERIAL" This issue arises only when using the autoIncrement=true parameter for the primary key. 'use strict'; export ...

What is the best way to handle multiple promises when loading a state in Angular?

When loading the /home state, I need to retrieve all users from the database in order to customize the home controller and view based on the logged-in user. Currently, in the :resolve section of the state configuration, I am fetching all 'posts' ...

Is it possible to track traffic using Alexa or SimilarWeb on a single-page application?

We are currently grappling with the challenge of how to effectively track traffic and user engagement within our classified sites on a single-page application built in angularJS. While we have successfully managed SEO and tracking with Google Analytics, we ...

Struggling to make ng-repeat function properly within an AngularJS controller when working with arrays

I am having trouble with my code. The ng-repeat in my AngularJS app is displaying blank. Can someone help me figure out why? Thanks in advance, Stephanie <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/aja ...

Transform a row into a clickable element

I am currently working on a social media platform where users can search for venues stored in the database. In my search.php file, I have implemented a text box that dynamically loads venue names from the database into a venuesearch div as the user types. ...

Is there a way to instruct Express to refrain from parsing the request's query string?

Is there a way to turn off Express's default behavior of parsing query strings and ignore them completely? I parse the query strings on the client side, and receiving a large number of requests with long query strings would be resource-intensive for t ...

Display the header on every single page using puppeteer

            Whenever I enable displayHeaderFooter, the header does not display. It only works if I add margin to @page in my CSS, but this causes the page height to increase by the margin value and content to overflow beyond the page boundaries. Is ...

Converting HTML and CSS into a PDF using JavaScript

I am on the lookout for libraries that can cater to my specific needs, as I haven't found one that fits perfectly yet. My setup involves Node.js on Express.js for the backend, and html/css/js for the front-end. Browser support includes IE8 and up, chr ...

Ensuring Radio Button Selection in C# WPF App with Error Management

Hello there! I've got a scenario where I have three radio buttons with values of 10, 20, and 30 respectively. The fourth radio button is labeled "Other" and has a text box next to it for users to enter any other numerical value they prefer. My goal is ...

Angular directive - observing changes in dynamically grouped models

How can I make similar models in a group watch each other for changes dynamically, with an unspecified number of members in each group? For example, if one input is filled, it should auto-fill any other empty inputs in the same group. The goal is to have c ...

JavaScript does not show an error message if a function is called but has not been defined

Currently, I am developing a nodejs/reactjs application that incorporates a cache system. During my development process, I encountered an interesting error where the data stored in the cache was not being displayed by the component. After thorough investig ...

Showing an array in an ASPX page using C# codebehind

Having a string array of survey responses called "answers" poses a challenge. For example, the answers array is defined as follows: string[] answers = new string[10] {"Y", "Y", "N", "Y", "N", "Y", "N", "Y", "N", "Y"}; In order to display each individua ...