angularjssortingfilterhtml-tableng-filter

Sort IP Address AngularJS


I have a table header IP Address, that use AngularJS to sort it. Unfortunately, it doesn't seem to sort IP address.

<th class="text-left">
    <a href="" ng-click="sortType = 'device.ip_address'; sortReverse = !sortReverse">
        IP Address
    </a>
</th>

enter image description here

I want to use something like this

sortFn: function (a, b) {
    if (a == b) return 0;
    if ( +a.replace(/\./g, '') < +b.replace(/\./g, '')) return - 1;
    return 1;
}

How do I use this function above as my sort function in AngularJS?


Solution

  • You should normalize IPs (for example, from 192.168.1.1 to 192.168.001.001) to properly compare them:

    angular.module('app', []).controller('ctrl', function($scope) {
      $scope.ips = [
        "192.168.1.1",
        "192.168.2.3",
        "192.168.1.00",
        "192.168.1.3"
      ]
      $scope.sortIps = function(ip) {    
        return ip.split('.').map(function(x) {
          return x.padStart(3, "0");
        }).join('');
      }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
    </script>
    
    <div ng-app='app' ng-controller='ctrl'>
      <a ng-init='sortReverse=false' href="" ng-click="sortReverse = !sortReverse">
          IP Address
      </a>  
      <ul>
        <li ng-repeat='ip in ips | orderBy : sortIps : sortReverse'>{{ip}}</li>
      </ul>
    </div>