Angular: Custom Sort Using d3js Example

http://angularjs.org/

by Matthew Marcus

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.4.0/d3.min.js"></script>
<div ng-controller="MyCtrl">
    <input ng-model="filterTxt" type="text" /><br />
    <table>
        <thead>
            <tr>
                <th ng-click="sort('name')">name:</th>
                <th ng-click="sort('age')">age:</th>
                <th ng-click="sort('a')">a:</th>
                <th ng-click="sort('b')">b:</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="item in arr | filter:filterTxt">
                <td>{{item.name}}</td>
                <td>{{item.age}}</td>
                <td>{{item.subObj.a}}</td>
                <td>{{item.subObj.b}}</td>
            </tr>
        </tbody>
    </table>
</div>

CSS

th,td{
    padding:3px;
}
th{
    cursor:pointer;
}

JavaScript

var myApp = angular.module('myApp', []);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

myApp.controller('MyCtrl',function($scope) {
    $scope.arr = [{
        name: 'Matt',
        age: 33,
        subObj: {
            a: 1,
            b: 2
        }
    }, {
        name: 'Sarah',
        age: 32,
        subObj: {
            a: 3,
            b: 4
        }
    }, {
        name: 'Savannah',
        age: 2,
        subObj: {
            a: 6,
            b: 1
        }
    }, {
        name: 'Caleb',
        age: 1,
        subObj: {
            a: 7,
            b: 3
        }
    }];
    
    $scope.sort = function(column){
        $scope.arr.sort(function(a, b){
            return (column == 'a' || column == 'b') ?
                d3.ascending(a.subObj[column], b.subObj[column]) : 
                d3.ascending(a[column], b[column]);
                
        });
    };
});