Ordering AngularJS by property name with spaces

While working with the MEAN stack and jade, I encountered an issue with AngularJS when using ng-repeat, ng-click, and orderby to sort columns in a table. Everything was working well until I tried sorting by a column named "To Do" which contains a space. This led to a syntax error in Chrome when trying to order by that specific column.

Despite finding some similar posts about handling properties with spaces, none of the solutions seem to work for me.

Jade: (Here is how I have set up ng-click, orderBy, and ng-repeat in Jade)

table
  caption {{collectionName}}
  thead
    tr
      th(ng-repeat="column in columns" ng-click="setPredicate(column);")
        {{column}}
  tbody
    tr(ng-repeat="row in rows | orderBy:predicate:reverse")
      td(ng-repeat="column in columns")
        {{row[column]}}

Controllers.JS: (This is where data for columns and rows is received in Angular and orderBy predicate changes happen)

$http.get('/api/collection/' + $routeParams.collectionName)
  .success(function(data){
    $scope.collection = data;
    $scope.columns = data.columns;
    $scope.rows = data.rows;
    console.log(data);
  });


$scope.setPredicate = function(column){
  if (column === "To Do"){
    var keys = Object.keys($scope.rows[0])
    $scope.predicate = keys[1]; 
    // $scope.predicate = "To Do"; 
    // $scope.predicate = column[$scope.columns];
  }else{
    $scope.predicate = column;
  }
  $scope.reverse = !$scope.reverse;
}

NodeJS index.JS: (How columns array and rows are sent to Angular from MongoDB)

router.get('/api/collection/:collectionName', function(req, res){
  collectionProvider.findCollection(req.param('collectionName'), function(error, documents){
    var keys;
    if(documents[0]){
      keys = Object.keys(documents[0]);
      remove(keys,'_id');
    }
    res.json({
      columns: keys,
      title: req.param('collectionName'),
      rows:documents,
      collectionName: req.param('collectionName')
    });
  });
});

In summary, each column header in my table corresponds to a property representing the data in that column. Node dynamically retrieves all the properties of the first record and sends an array of property names to $scope.columns in Angular. When a column heading is clicked, a predicate switches the orderBy sorting accordingly.

This being my initial experience with angular, I had expected to directly use ng-click="predicate=column" in Jade but had to resort to sending it to a controller function instead. I am unsure if this approach aligns with best practices in Angular development.

Answer №1

To properly use the orderBy predicate, it should be a function that takes the collection as an argument, accesses the desired property using bracket notation, and then returns the value of that property.

In your specific case, the setPredicate function needs to set the value of the property used by the predicate.

Here's an example implementation:

JS:

// Default orderBy
$scope.orderBy = $scope.columns[0];

$scope.setOrderBy = function (column) {
  $scope.orderBy = column;
}

$scope.predicate = function(rows) {
  return rows[$scope.orderBy];
}

HTML:

<th ng-repeat="column in columns" ng-click="setOrderBy(column)">{{ column }}</th>

And:

<tr ng-repeat="row in rows | orderBy:predicate:reverse">

Demo: http://plnkr.co/edit/2Mlc2lBf0wRVicfcfYZO?p=preview

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

Disable the smooth scroll animation when transitioning between pages using the Link component in NextJS

Not sure if this is a new feature of Next.js, as I didn't encounter this issue in my previous Next.js project. When I reach the bottom of a page and try to navigate to another page, a scroll-to-top animation appears on the destination page. I want to ...

Tips for keeping the hover effect of a sibling element in Material-UI

Card Component import image from "../../Assets/pic.jpg"; import React, { useState } from "react"; import { makeStyles } from "@material-ui/core/styles"; import Card from "@material-ui/core/Card"; import CardActionAre ...

Passing large arrays of data between pages in PHP

I'm facing a challenge where I need to pass large arrays of data between pages. Here's the situation: Users input their Gmail login details in a form, which is then sent to an AJAX page for authentication and contact retrieval. If the login fail ...

What is the best way to apply absolute positioning to an image tag that is related to

I'm completely new to both rails and javascript. In my app, I have a table of venues categorized by type and area. These venues are displayed as partials on the index page, each with its own icon that appears on a map located to the left of the screen ...

Is it not possible to change node labels in D3.js after clicking on a node?

After being inspired by this link, I successfully created a basic network visualization app using D3.js. The app reads node names from a textarea on an HTML page and then constructs a network where all nodes are interconnected. All the relevant code can ...

Is browserHistory.push ineffective in react.js?

I am currently working on a React ecommerce website. I have encountered an issue in the login component where, upon clicking the submit button on the form, the system is supposed to check if the user is authenticated using useEffect. If the user is authent ...

Steps to avoid TypeError: e.target.getAttribute is not a function

My goal is to make the inner code (result) function only when a Validity attribute is present. However, my target lacks said attribute, so I'm looking for a way to use an if statement to prevent the inner code from executing. How can I avoid the Type ...

Tips on making MySQL requests from Angular applications

Initially, this is not a specific query but more of a how-to question. I am starting an AngularJS app from scratch and I'm trying to modify an SQL query from within Angular. So far, I've only come across examples of how to retrieve data from a s ...

Navigating through the exported components of a module without explicit type declarations

So I'm in the process of developing a module with sub-modules for Angular. Here's the notation I'm using: module App.services { export class SomeService { } } When initializing all services, I use the following code snippet: function ...

When using ng-checked in Angular, the DOM may not display the element.input.checked property even when the

I am having issues with using ng-checked to automatically check a checkbox when a modal loads under certain conditions. Despite the item being checked, the condition if (item.checked) returns false. Below is the directive I am working with. app.directive ...

Unable to retrieve data from Meteor find query

I have a collection created in collections.js portfolioItems = new Mongo.Collection('portfolioitems'); This collection is then subscribed to in subscriptions.js Meteor.subscribe('portfolioitems'); And published in publications.js M ...

When utilizing the .populate() method in Mongoose, how can you retrieve and append ObjectIds with extra attributes to an array (which is returned by .populate()) collected from the

When using the .populate() method in Mongoose, how can I retrieve and add ObjectIds with additional properties to an array (returned by .populate()) if their corresponding document in the collection no longer exists? This question pertains to MongoDB and ...

Drawing recursive 2D tree fractals using WebGL technology

Attempting to create a binary fractal tree in webgl, but struggling with the branch angles not aligning as desired. The approach involves plotting vertex points into an array, converting it into a float32array, and then utilizing drawArrays(LINE_STRIPE) fo ...

Most effective method to retrieve yesterday's data

Currently, I'm working on a requirement and I need to validate the logic that I've implemented. Can someone help me with this? The task at hand is to calculate the 1 month, 3 month, and 6 month return percentages of a stock price from the curren ...

collapse each <b-collapse> when a button is clicked (initially shown)

I am facing an issue with a series of connected b-buttons and b-collapse, all initially set to be visible (open). My goal is to hide them all when a toggle from my parent.vue component is activated - so upon clicking a button in the parent component, I wa ...

Tips for Iterating through Nested Arrays using the Inside Array in a Dynamic Way

I am facing an issue with my code as it lacks flexibility when a new array is added to the nested array, in which case the new array is not considered. My main concern is how to access the elements of each nested array simultaneously. Here's an examp ...

Using Slick.JS to Sync Navigation with Main Slider, Automatically Resetting to First Slide

I have a question about the functionality of the Slick.JS plugin that I'm using. In my project, I have two carousels with five slides each. The top carousel displays one slide at a time, while the bottom carousel shows all five slides concurrently. My ...

Transferring data between jQuery and other global JavaScript variables

I'm facing a challenge when trying to make functions I created in jQuery access JavaScript values defined elsewhere. For instance, I have a function set within my jQuery code. var parentImg = ''; //global variable. $(document).change(funct ...

How to Use Radio Buttons in Material-UI to Disable React Components

Just starting out with ReactJS and Material-UI, I've been experimenting with them for about 3 weeks. Currently, I'm facing a challenge where: - There are 2 radio buttons in a group and 2 components (a text field and a select field); - The goal is ...

The variable declared in the useState hook is not being properly updated within the callback function

const ModifiedTweet = ({ tweet, checkedList, setCheckedList }) => { const [isChecked, setChecked] = useState(false); useEffect(() => { if (checkedList.length === 0) { setChecked(false); } }, [checkedList, isChecked]); return ( ...