4

私は AngularJS を初めて使用しますが、これまでのところ、すべてについて頭を悩ませることができました。しかし、OrderBy が問題を引き起こしています。そして、私はまだ私のような問題を見つけていません。$scope と orderBy が実際にどのように機能するかについて何かが欠けているためだと感じています。

今年の NaNoWriMo の私の地域の作家を表示するリストを作成しています。ユーザーをファクトリーに分けて表示させました。しかし、私はそれらをソートするのに問題があります。Name と Wordcount は問題なくソートされます。しかし、Calculated Average Wordcount はまったくソートされていません。私が作成した関数を呼び出すことさえありません。

これが私の簡略化されたレイアウトと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>

4

2 に答える 2

1

Average WPD 見出しをクリックすると、$scope.sort が文字列"avgWords" に設定されます。したがって、orderBy はこの文字列を使用してユーザーを並べ替え、avgWordsフィールドの値 (常に ) でユーザーを並べ替えますundefined

フィールドではなくカスタム関数を使用して並べ替えたい場合は、並べ替えに使用する$scope.sort関数を設定する必要があります。

$scope.sort = $scope.avgWords;

これを行うには、見出しの ng-click を次のようにする必要があります。

sortChange(avgWords)
于 2014-10-16T16:55:52.003 に答える