Monday, September 8, 2014

Sorting with reversing sort order table columns interactively using angular js

<html ng-app="countryApp">
  <head>
    <meta charset="utf-8">
    <title>Angular.js Example</title>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <script>
      var countryApp = angular.module('countryApp', []);
      countryApp.controller('CountryCtrl', function ($scope, $http){
        $http.get('countries.json').success(function(data) {
          $scope.countries = data;
        });

        $scope.sortField = 'population';
        $scope.reverse = true;
      });
    </script>
  </head>
  <body ng-controller="CountryCtrl">
    Search:<input ng-model="query" type="text"/>
    <table>
      <tr>
        <th><a href="" ng-click="sortField ='name'; reverse = !reverse">Country</a></th>
        <th><a href="" ng-click="sortField = 'population'; reverse = !reverse">Population</a></th>
      </tr>
      <tr ng-repeat="country in countries | filter:query | orderBy:sortField:reverse">
        <td>{{country.name}}</td>
        <td>{{country.population}}</td>
      </tr>
    </table>
  </body>
</html>




another one example

<html ng-app="orderByExample">
  <head>
    <meta charset="utf-8">
    <title>Angular.js Example</title>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>  
  </head>
  <body>
 
    <script>
        angular.module('orderByExample', [])
            .controller('ExampleController', ['$scope', function($scope) {
          $scope.friends =
              [{name:'John', phone:'555-1212', age:10},
               {name:'Mary', phone:'555-9876', age:19},
               {name:'Mike', phone:'555-4321', age:21},
               {name:'Adam', phone:'555-5678', age:35},
               {name:'Julie', phone:'555-8765', age:29}];
          $scope.predicate = '-age';
        }]);
    </script>
    <div ng-controller="ExampleController">
      <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
      <hr/>
      [ <a href="" ng-click="predicate=''">unsorted</a> ]
      <table class="friend">
        <tr>
          <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
              (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
          <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
          <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
        </tr>
        <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
          <td>{{friend.name}}</td>
          <td>{{friend.phone}}</td>
          <td>{{friend.age}}</td>
        </tr>
      </table>
    </div>
   
   
  </body>
</html>

No comments: