I'm new to AngularJS, but so far I've been able to wrap my head around everything. But the OrderBy is causing me issues. And I haven't found any issues like mine yet. I have a feeling it's because I'm missing something about the $scope and how orderBy actually works.
I'm creating a list that will display writers in my region for this years NaNoWriMo. I've separated the users as Factories, and have gotten them displayed. But, I'm having issues getting them sorted. The Name and Wordcount sort without a problem. But the Calculated Average Wordcount is not sorting at all. It won't call the function I've made for it, even.
Here's my simplified layout, and the JSFiddle setup (updated).
JS:
(function () {
var app = angular.module('userList', []);
app.controller('ListController', ['$scope',
function ($scope) {
$scope.users = userData;
$scope.day = 30;
$scope.avgWords = function (user) {
return Math.floor(user.wordcount / $scope.day);
};
$scope.sort = "name";
$scope.sortRev = false;
$scope.sortChange = function (field) {
if ($scope.sort === field) {
$scope.sortRev = !$scope.sortRev;
return;
}
$scope.sort = field;
$scope.sortRev = false;
};
$scope.sortAvg = function (user) {
alert("sorted!");
return Math.floor(user.wordcount / $scope.day);
};
}]);
var userData = [{
"name": "Kris",
"wordcount": 42382
}, {
"name": "Tim",
"wordcount": 60120
}, {
"name": "Elsa",
"wordcount": 150675
}];
})();
HTML:
<div ng-controller="ListController">
<table>
<thead>
<tr>
<th ng-click="sortChange('name');">Username</th>
<th ng-click="sortChange('wordcount');">Total Words</th>
<th ng-click="sortChange('sortAvg');">Average WPD</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users | orderBy:sort:sortRev">
<td>{{user.name}}</td>
<td>{{user.wordcount}}</td>
<td>{{avgWords(user)}}</td>
</tr>
</tbody>
</table>
When you click on the Average WPD heading, you set $scope.sort to the string "avgWords". So, orderBy uses this string to sort the users, and thus orders the users by the value of their avgWords
field, which is always undefined
.
If you want to sort using a custom function rather than a field, you must set $scope.sort
to the function you want to sort by:
$scope.sort = $scope.avgWords;
To do that, the ng-click on the heading should be
sortChange(avgWords)