Sorting function not working on dynamic Angular table

I'm currently facing a challenge with sorting a dynamic Angular table.

If I manually code the table headers, everything works smoothly. Fiddle: https://jsfiddle.net/xgL15jnf/

<thead>
    <tr>
        <td>
            <a href="#" ng-click="sortType =  'id';    sortReverse = !sortReverse">id
                <span   ng-show="sortType  == 'id' && !sortReverse" class="glyphicon glyphicon-arrow-down"></span>
                <span   ng-show="sortType  == 'id' &&  sortReverse" class="glyphicon glyphicon-arrow-up"></span>
            </a>
        </td>
        <td>
            <a href="#" ng-click="sortType =  'name';    sortReverse = !sortReverse">name
                <span   ng-show="sortType  == 'name' && !sortReverse" class="glyphicon glyphicon-arrow-down"></span>
                <span   ng-show="sortType  == 'name' &&  sortReverse" class="glyphicon glyphicon-arrow-up"></span>
            </a>
        </td>
        <td>
            <a href="#" ng-click="sortType =  'cost';    sortReverse = !sortReverse">cost
                <span   ng-show="sortType  == 'cost' && !sortReverse" class="glyphicon glyphicon-arrow-down"></span>
                <span   ng-show="sortType  == 'cost' &&  sortReverse" class="glyphicon glyphicon-arrow-up"></span>
            </a>
        </td>
    </tr>
</thead>

However, when I try to generate the headers dynamically, the sorting doesn't function as expected. Fiddle: https://jsfiddle.net/m31d00sz/

<thead>
    <tr>
        <td ng-repeat="column in cols">
            <a href="#" ng-click="sortType = '{{column}}';    sortReverse = !sortReverse">{{column}}
                <span ng-show="sortType   == '{{column}}' && !sortReverse" class="glyphicon glyphicon-arrow-down"></span>
                <span ng-show="sortType   == '{{column}}' &&  sortReverse" class="glyphicon glyphicon-arrow-up"></span>
            </a>
        </td>
    </tr>
</thead>

The Search/Filter feature functions correctly in both of the provided Fiddles.

I believe there might be a simple solution that I am overlooking, and would greatly appreciate any assistance or guidance on this matter!

Answer №1

When using the ngClick directive, there is no need to include interpolation braces like {{column}}. The correct syntax should be:

ng-click="sortType = column; sortReverse = !sortReverse"

One issue to be aware of is that each iteration created by the ngRepeat directive generates new child scopes. Therefore, clicking will modify the local scope properties sortReverse and sortType. To address this, you can utilize prototypical inheritance so that ngClick accesses properties from upper scopes resolved by the prototype chain.

To achieve this in the controller, define:

$scope.sort = {
    type: 'id',
    reverse: false
};

And in the template:

<td ng-repeat="column in cols"> 
    <a href="#" ng-click="sort.type = column; sort.reverse = !sort.reverse">
        {{column}}
        <span ng-show="sort.type == column && !sort.reverse" class="glyphicon glyphicon-arrow-down"></span>
        <span ng-show="sort.type == column && sort.reverse" class="glyphicon glyphicon-arrow-up"></span>
    </a>

</td>

Also, include:

<tr ng-repeat="row in rows | orderBy:sort.type:sort.reverse | filter:searchData">
    <td ng-repeat="column in cols">{{row[column]}}</td>
</tr>

Check out the demo here: https://jsfiddle.net/m31d00sz/1/

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

The select2 does not show the selected information

My select2 is not selecting the value when in edit mode. You can view my data here. Upon clicking the edit data button, it should select "settings" as the parent's value, but unfortunately, it's not working. You can see the issue here. Modal Sc ...

Tips for effectively downsizing an HTML Canvas to achieve high-quality images

Introduction I am currently facing issues with blurry visuals in my canvas animation, especially on devices with high pixel densities like mobile and retina screens. In order to address this problem, I have researched canvas down-scaling techniques and f ...

Switching between rows in a table once information has been added to an array | Vue

I'm currently working on creating a table with rows that toggle when a 'View' button is clicked. The table is generated using a for loop for an array. I've successfully implemented the toggling functionality for preloaded data, but enco ...

Need help setting up automatic audio playback on your Android device?

I'm aware that autoplay of audio is not supported on Android devices. However, I recently found a website that successfully autoplays music on an Android device: Can someone explain how this is being achieved? ...

I am unable to integrate Autoprefixer into an Express project

I am having trouble adding Autoprefixers to the postcssmiddleware, as mentioned in the documentation here I also attempted using express-autoprefixers but still cannot see the vendors in my dest or public folder. You can find a link to my repository (node ...

Looking to incorporate Slick Carousel as the main slider on my website for a dynamic hero section using JavaScript

Currently in the process of expanding my knowledge in javascript, I am now delving into setting up Slick Carousel. It is essential that it functions as a hero slider on my website. If you are interested in checking out Slick Carousel on github, feel free ...

How can the execution of a directive within another directive's template be triggered?

Is there a way to declare a directive within another custom directive template? The goal is for the inner directive to utilize a field from the outer directive's scope: angular.module('core.directives') .directive('containertable&apos ...

Issues with invoking C# event through ajax communication

Whenever I click the Button, an Ajax method is called that triggers a webmethod on the server side. However, currently, the [WebMethod] is not being executed as expected. Below are the snippets of both the Ajax and server-side code: Ajax code $(document ...

Observing a method with input parameters in Angular

As I go through a list of Jobs, the process is pretty simple (I've simplified it here as an example). It's easy to access information from the Jobs array, like this (Job.Name, Job.Date, etc.) <div ng-repeat="(key, Job) in Jobs" ng-show="Jo ...

Knockout JS: Choosing specific dropdown elements

My array doorsForSite contains a list of doors, each with its own set of schedules. Here is how it looks: var scheduleList = new[] { new { ScheduleId = "Schedule1",ScheduleName = "Always On" }, new ...

Six Material-UI TextFields sharing a single label

Is there a way to create 6 MUI TextField components for entering 6 numbers separated by dots, all enclosed within one common label 'Code Number' inside a single FormControl? The issue here is that the label currently appears only in the first tex ...

Having issues making div elements with javascript

I am having trouble generating new divs when a specific div is clicked. Despite my efforts, nothing seems to be happening and the console isn't showing any errors. I've searched online for solutions but haven't found anything that addresses ...

"Trouble encountered while trying to display Angular in an HTML document

In my Angular project, there is a feature where a list of orders is displayed in one view. Each order is represented by its title only. When the user clicks on the title, they should be redirected to a new view showing the complete content of that particul ...

"Enhance your Angular application with Datatables using $http to fetch and display data

Currently, I'm working on a project with AngularJS where I'm fetching data from the server using the $http service. Here's a snippet of the code: $http({ method: 'GET', url: $rootScope.apiURL + 'getAllClientLocations/ ...

Exploring the parent scope in handlebars.js partials

Is there a way to access the parent scope from a partial using #each in Handlebars? Main template: (out of each = {{index}})<br> {{#each someItem}} (in each, but not on partial = {{../index}}) {{>part}} {{/each}} Partial: <div class="part ...

"PHP script for submitting a form with a post button

Can anyone help me figure out why the submit function isn't working? I've been trying to solve the problem with no luck so far. Any ideas on what might be causing this issue? <?php if(isset($_POST['submit'])){ echo ("Submit fun ...

What is Node.js's approach to managing concurrent operations?

Recently, I've been engrossed in this fascinating book that delves into JavaScript. In one section, it emphasizes that Node.js stands out due to its unique single-threaded event-based concurrency through an asynchronous-by-default API. I find it puz ...

angularjs issue with $setPrestine function not providing reliable results

I have encountered an issue with the login form code. Initially, I am able to reset the form fields and error messages successfully on the first attempt (both success and failure scenarios work). However, on the second try, I am unable to reset the form fi ...

Troubleshooting: Custom AngularJS directive not responding to ng-click event

I recently developed a custom directive, and while the controls defined in the templates are working smoothly, I encountered an issue. I needed to add an additional control - an image button, based on a certain condition. To achieve this, I utilized an IF ...

The Node.js application is unable to execute due to the error: "View "error" could not be found in the views directory."

Currently, I am following a tutorial that covers the integration of social login with Passport and Node. You can find the tutorial here: Tutorial Link In line with the tutorial, I have started working on a project while utilizing Windows 10 operating syst ...