Search code examples
javascriptangularjssortingangularjs-orderby

angularJS: Dynamic header sorting not working


I am trying to implement a solution to sort a table by clicking its headers, using AngularJS.

I found a good example after doing a Google search: https://scotch.io/tutorials/sort-and-filter-a-table-using-angular

I am able to see the up and down arrows, but the table does not sort when I click them.

I think the problem resides in how the JSON object is formatted in my situation. I have not been able to figure it out, and I am hoping that with the information that I am providing on this post, I can get some help to understand what I am doing incorrectly.

Here is a copy of the JavaScript:

    (function (define, angular) {
    'use strict';
    define(function () {

        var opportunityController = function ($scope, Metadata, Factory) {

            var vm = this;

            //set the default sort type
            vm.sortType = 'Products';            

            //set the default sort order
            vm.sortReverse = false;             

            Factory.Data(caller.sp, caller.filter).then(function (payload) {
                var data = angular.fromJson(payload.data).Table;
                ProcessData(data);
            });

            function ProcessData(data) {
                if (angular.isDefined(data)) {
                    var counter = 0;
                    vm.products = [];
                    vm.productsSet = FindByAsObjectArray(function (x) {
                        return (x.TypeName == "Product");
                    }, data);

                    for (var index = 0, length = vm.productsSet.length; index < length; index++) {
                        vm.products[index] = {
                            data: vm.productsSet[index]
                        };                                                
                    }
                }                    
            }
        };
        return ['$scope','Metadata','Factory',opportunityController];
    });
})(define, angular);

I got it to work, final version: https://jsfiddle.net/itortu/nhhppf53/

Many thanks.


Solution

  • You are using controllerAs

    ng-controller="Company:OpportunityController as opportunity"
    

    therefor you have to reference sortType and sortReverse in your ng-click like so:

    ng-click="opportunity.sortType = 'Products'; opportunity.sortReverse = !opportunity.sortReverse"