显示数组摘要

show summary of array

我有一个面额列表,每个面额都可以加一卷。当我单击按钮添加角色时,它会执行以下操作:

$scope.addRoll = function (type) {
    $scope.rollArray.push({
        "type": type,
        "value": utilityFactory.getByLabel(type).clipValue
    });
}

HTML 输出当前为

<ul class="rollList">
    <li ng-repeat="rolls in rollArray"><span>{{rolls.type}} | {{'$' + rolls.value.toFixed(2)}}</span></li>
</ul>

在 UI

上看起来像这样

我宁愿能够展示类似的东西:

有没有办法使用 ng-repeat 将相同的元素分组并计算总数?

要创建聚合,它可以像倒排索引一样简单:

$scope.rollArray = [];
$scope.index = {};

var invertCounts = function(rollArray) {
    var object = {};

    for(var i in rollArray) {
        var type = rollArray[i].type;
        if(angular.isUndefined(object[type])) {
            object[type] = { count: 0, items: [], sum: 0.0 };
        }

        object[type].count++;
        object[type].items.push(rollArray[i]);
        object[type].sum += rollArray[i].value.toFixed(2)
    }

    return object;
}

$scope.addRoll = function (type) {
    $scope.rollArray.push({
        "type": type,
        "value": utilityFactory.getByLabel(type).clipValue
    });
    
    $scope.index = invertCounts($scope.rollArray);
};

以下为HTML

<ul>
    <li ng-repeat="(type, value) in invertCounts(rollArray)">
        {{ value.count + ' ' + type + ' -> ' + value.sum }}
    </li>
</ul>

这不是一个完美的解决方案,但它是您如何实现的粗略实现。

更新

糟糕,这行不通忘记了刚刚在 jsfiddle 中测试过它:

http://jsfiddle.net/dmcquillan314/8nfLtxsw/