What is the significance of using sortBy in ng-click?

Recently, I've been delving into AgularJS and took on a practice exercise:

JS file:

function CustomersController() {
    this.sortBy = 'name';
    this.reverse = false;

    this.customers= [{joined: '2000-12-02', name:'John', city:'Chandler', orderTotal: 9.9956}, {joined: '1965-01-25',name:'Zed', city:'Las Vegas', orderTotal: 19.99},{joined: '1944-06-15',name:'Tina', city:'New York', orderTotal:44.99}, {joined: '1995-03-28',name:'Dave', city:'Seattle', orderTotal:101.50}];
    this.doSort = function(propName) {
       this.sortBy = propName;
       this.reverse = !this.reverse;
    };
}

HTML file:

<!doctype html>
<html ng-app="customersApp">
<head>
    <title>Iterating Over Data</title>
    <link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body ng-controller="CustomersController">
    <h2>Customers</h2>
    Filter: <input type="text" ng-model="customerFilter.name" />
    <br /><br />
    <table>
        <tr>
            <th ng-click="doSort('name')">Name</th>
            <th ng-click="doSort('city')">City</th>
            <th ng-click="doSort('orderTotal')">Order Total</th>
            <th ng-click="doSort('joined')">Joined</th>
        </tr>
        <tr ng-repeat="cust in customers | filter:customerFilter | orderBy:sortBy:reverse">
            <td>{{ cust.name }}</td>
            <td>{{ cust.city }}</td>
            <td>{{ cust.orderTotal | currency }}</td>
            <td>{{ cust.joined | date }}</td>
        </tr>
    </table>
    <br />
    <span>Total customers: {{ customers.length }}</span>

    <script src="angular.js"></script>
    <script src="app/app.js"></script>
    <script src="app/controllers/customersController.js"></script>
</body>
</html>

When I interact with the webpage, I'm able to sort the data by clicking on the table's headers. This led me to wonder about the role of "sortBy". Is it an inherent variable within $scope? I experimented with renaming it (e.g., "sortby") but observed that it only triggered reversal rather than sorting. If indeed built-in, where can I access the predefined functions of $scope? Your insights are greatly appreciated!

Answer №1

Firstly, sortBy is simply the label given to a variable and is not inherently part of the $scope. Any name can be used instead. It's important to note that sortBy appears in two locations:

In the HTML:

<tr ng-repeat="cust in customers | filter:customerFilter | orderBy:sortBy:reverse">

And in your controller in two instances:

// This sets up the initial sorting order
this.sortBy = 'name';
// This updates the sorting order when a user clicks on a table heading
this.sortBy = propName;

You have the flexibility to choose a different name for sortBy; just make sure to replace it in all instances where it appears.

On the other hand, orderBy is specifically related to ng-repeat and cannot be modified. For further details, refer to the final example on this page: https://docs.angularjs.org/api/ng/directive/ngRepeat

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

Guide to exporting specific files in Node.js or Deno

Utilizing the export keyword in JavaScript allows us to export any content from one file to another. Is there a way to restrict exports to specific files, preventing other files from importing them? export const t = { a: 'this will only be exported fo ...

Combining arrays into an Object with zipped keys and values

I have some data that I am working with var foo = ['US','MX','NZ']; var foo1 = [12',13',17]; var Object = {}; I attempted a solution by doing the following var Object = {foo:foo1} Unfortunately, this approa ...

Dynamic menu plugin for JQuery

I am still new to jQuery and currently learning how to efficiently use it in website development. I am currently working on implementing a responsive navigation plugin that I came across online. However, I have encountered an issue with the plugin where th ...

Can you explain the purpose of useEffect in React?

As a beginner in learning React, I have been able to grasp the concept of the useState hook quite well. However, I am facing some difficulties understanding the useEffect hook. I have tried looking through the documentation, searching online, and even wat ...

What is the best method for incorporating multiple jQuery ready() functions?

Trying to develop a web application with HTML files that require multiple JS files. Need to specify tasks inside jQuery.ready() in each JS file, but unable to define $(function () {}) more than once. Is there a way to modify the passed function? index.pug ...

PHP and AJAX failed to retrieve post data

I encountered some puzzling issues when attempting to send post data to a php file using xmlhttp request: Below is the javascript code snippet: function getHeaterDailyConfig(){ var oReq = new XMLHttpRequest(); var d = new Date() now = [d.g ...

Unable to retrieve data from my json file in React

I have successfully created a menu with a submenu and a third child element. Initially, I had hard-coded the data in a local constant called json, which is now commented out. However, I am facing an issue as I now need to fetch the data from my JSON file b ...

Is it possible to execute an AngularJS project without using Gruntjs?

Is it possible to run my AngularJS project without Gruntjs? If so, could you please provide instructions on how to do so? I am running the project on a windows machine and have already installed node.js and eclipse mars 4.5. ...

Uncovering the Mystery: The Issue of Duplicate Items When Writing Arrays to localStorage in JavaScript

Struggling to create a Javascript quiz for my coding bootcamp. I'm facing challenges with retrieving and saving previous high scores from local storage. Can someone explain why the newScore is being written TWICE to the highScores arrayItems array in ...

JavaScript Checkbox function: "error: property id missing a colon"

Recently, I've been dabbling in javascript and I've hit a roadblock that I cannot seem to overcome. I decided to try my hand at using the ajax functions from jquery, but I got stuck on a specific piece of code. My goal is that when a checkbox is ...

The Stepper StepIconComponent prop in MUI is experiencing issues when trying to render styles from the styles object, leading to crashes in the app

Struggling to find a way to apply the styles for the stepper component without using inline styles. I attempted to replicate Material UI's demo, but encountered an error. The code from Material UI's demo that I want to mimic is shown below: http ...

Using setTimeout() in JavaScript to create a delay between functions

Is there a way to add a delay between the execution of each function in my program? Currently, I have the following setup: function function0() { setTimeout(function1, 3000); setTimeout(function2, 3000); setTimeout(function0, 3000); } While t ...

Issue with Vue CLI 3: the hot reloading feature is causing significant delays in rebuilding the project

After updating a major project to utilize Vue CLI 3, I've noticed that the hot reloading process has become exceptionally slow: Upon opening a .vue file, it automatically rebuilds without any prompt, taking up to 10-15 seconds each time Whenever I s ...

Passing data between multiple components in ReactJs by utilizing the Id field

Is there a way to transfer data from the Main Component to a child component based on the record Id? I have an index.js and detail.js pages set up. On the index page, I include a link like this: <Link to={{ pathname:/cards/${results.id}, state: result ...

Comet spinning in orbit around celestial body

I need help creating a game where an object (comet) can fly and rotate around another object (planet) in orbit. Currently, I have managed to make the comet move and turn towards the planet, but I am struggling to figure out how to make it start rotating ar ...

Is it possible to have two different actions with two submit buttons in PHP?

Here is my form tag: sample name:register.php page <form id="formElem" name="formElem" action="form10.php" method="post"> <input id="pd" name="pd" type="text" AUTOCOMPLETE=OFF /> <input id="pd1" name="fname" type="text" AUTOCOMPLETE=OFF /& ...

Struggling to create a web application using parcel-bundler (Java not loading post-compilation)

Hey everyone, I've been searching online for a solution to my problem with parcel while working on a bootstrap web project, but I haven't had any luck. So now, I'm reaching out to you all for help. Bear with me as I explain the situation in ...

Looking to screen usernames that allow for the use of the DOT (.), underscore (_), and Dash (-)?

I am using jQuery to filter usernames that are exactly 3 characters long. The validation criteria includes only allowing the following special characters: ., _, and - var filter = /^[a-zA-Z0-9]+$/; Therefore: if (filter.test(currentval)) { //valid ...

I'm currently trying to scrape websites that have JavaScript enabled, but I'm having trouble extracting any content from them

from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import ...

Check for nested objects while watching - NuxtJS (Vue) in its most recent release

My form is connected to a data object called this.myData: data: function() { return { isDataChanged: false, myData: {}, myChangedData: { default: '', default1: {}, default2: [] }, } }, The values in ...