我是 AngularJS 的新手,但到目前为止,我已经能够理解所有内容。但是 OrderBy 给我带来了问题。而且我还没有发现像我这样的问题。我有一种感觉,这是因为我缺少有关 $scope 以及 orderBy 实际工作方式的一些信息。
我正在创建一个列表,显示我所在地区今年 NaNoWriMo 的作家。我已将用户划分为工厂,并显示它们。但是,我在整理它们时遇到了问题。名称和字数排序没有问题。但是计算的平均字数根本没有排序。它甚至不会调用我为它创建的函数。
这是我的简化布局和JSFiddle 设置(更新)。
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>