AngularJS - 从JSON过滤最大的价值

时间:2014-06-10 10:12:03

标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

我有一个带有数值列表的JSON文件:

{
    "Entries": {
        "Records" : [
            {
                "Name": "Mr Happy",
                "Gender": "Male",
                "Balance": "100"
            },
            {
                "Name": "Mr Sad",
                "Gender": "Male",
                "Balance": "50"
            },
            {
                "Name": "Mrs Grump",
                "Gender": "Female",
                "Balance": "2000"
            },
            {
                "Name": "Mr Loud",
                "Gender": "Male",
                "Balance": "1000"
            } 
        ]   

    }
}

我可以通过简单的ng-repeat显示值列表:

<li ng-repeat="account in Entries.Records">

    {{ account.Name }},  {{ account.Balance }} 

</li>

但是如何修改/过滤此ng-repeat以仅显示余额最高的记录?


更新了完整的控制器和服务:

app.controller("MyController", function($scope, $http, getReportService) {

    $scope.EntriesRecords = [];

    getReportService.getReportData(function(data) {

        $scope.EntriesRecords = data.Entries.Records;

        $scope.maxBalanceAccount = findMaxBalanceAccount();
    });


    function findMaxBalanceAccount() {
        var result = null;
        for (var i = 0; i < $scope.EntriesRecords.length; i++) {
        var account = $scope.EntriesRecords[i];
            if (result == null || account.Balance > result.Balance) {
                result = account;
            }
        }
        return result;
    }

    console.log($scope.maxBalanceAccount);

});


app.factory('getReportService', function($http) {
    return {
        getReportData: function(done) {
            $http.get('/data/records.json')
            .success(function(data) { 
                done(data);
            })
            .error(function(error) {
                alert('An error occured');
            });
        }
    }
});

1 个答案:

答案 0 :(得分:4)

不要使用ng-repeat。使用控制器的功能查找具有最大余额的帐户,并将其存储在范围内:

function findMaxBalanceAccount() {
    var result = null;
    for (var i = 0; i < $scope.Entries.Records.length; i++) {
        var account = $scope.Entries.Records[i];
        if (result == null || account.Balance > result.Balance) {
            result = account;
        }
    }
    return result;
}

$scope.maxBalanceAccount = findMaxBalanceAccount();

现在您可以在模板中使用它:

{{ maxBalanceAccount.Name }},  {{ maxBalanceAccount.Balance }} 

请注意,变量和字段通常以JavaScript中的小写字母开头。