Search code examples
javascriptangularjssortinghtml-tableangularjs-orderby

Angular-JS table sorting not working when delimiter change from ng: to ng-


I've created an angular application for sorting of html tables based on ascii values. The application works fine but the problem is when i change the delimiter from 'ng:' to 'ng-' the sorting is not working . If the cause of this is in case of someother reason please pardon me...since im new to angular js

can anyone please tell me some solution for this

angular code with 'ng-' delimiter (Working Demo) - Sorting Not working

<div ng-controller="Main" ng-app="myApp">
<table border="1">
  <tr>
    <th><a href ng-click="sortBy('name')">Name</a></th>
    <th><a href ng-click="sortBy('phone')">Phone Number</a></th>
    <th><a href ng-click="sortBy('age')">Age</a></th>
    <th><a href ng-click="sortBy('date')">Date</a></th>
  </tr>
  <tr ng-repeat="friend in friends|orderBy:sort:reverse">
    <td>{{friend.name}}</td>
    <td>{{friend.phone}}</td>
    <td>{{friend.age}}</td>
    <td>{{friend.date}}</td>
  </tr>
</table>
</div>

Solution

  • The issue is how you are defining and using predicate and reverse.

    When you are using "this" inside this function they are defined within just the scope of this function and are not accessible outside of it.

    $scope.sortBy = function (field) {
        if (this.predicate != field) {
            this.predicate = field;
            this.reverse = false;
        } else {
            this.reverse = !this.reverse;
        }
    };
    

    I updated it to use a local predicate variable and a reverse property on the scope, so it can be used in the markup.

    var predicate;
    $scope.reverse = false;
    
    $scope.sortBy = function (field) {
        if (predicate != field) {
            predicate = field;
            $scope.reverse = false;
        } else {
            $scope.reverse = !$scope.reverse;
        }
    };
    

    updated fiddle: http://jsfiddle.net/rvdww/77/