【问题标题】:Filtered Dropdown (using select) With Accumulated Totals (ng-repeat)过滤的下拉列表(使用选择)与累计总数(ng-repeat)
【发布时间】:2014-10-25 05:34:34
【问题描述】:

希望有人能够对我的问题有所了解。我有一个显示许多用户的 AgularJS 下拉列表。根据您选择的用户,它将显示一些由用户 ID 引用的数据。一切都很好!没有问题。

我想尝试对这些结果进行一些数学运算。 In my example below, when a user is selected, it will show a day of the week, and a "score".我想尝试在每一行的末尾累积分数。

小提琴:http://jsfiddle.net/bfoyhycy/1

    <tr ng-repeat="eachItem in Data |filter: { id: selectedOption.id }">
        <td>{{eachItem.day}}</td>
        <td>{{eachItem.score}}</td>
        <td> <!---- NO IDEA WHAT TO DO HERE ----> </td>
    </tr>

我以为我可以引用数据并使用它的索引,但这不起作用,因为我正在根据“id”过滤它。因此,累计总数对于第一个用户是正确的,但对于其余用户来说是不正确的(如果您选择用户“Frank”,则可以看到这一点)。

小提琴:http://jsfiddle.net/bfoyhycy/2/

    <tr ng-repeat="eachItem in Data |filter: { id: selectedOption.id }">
        <td>{{eachItem.day}}</td>
        <td>{{eachItem.score}}</td>
        <td>{{Data[$index-1].score}}</td>
    </tr>

我想知道是否有办法在 ng-repeat 期间获取上一行的值?我最初认为你可以做一个 {{eachItem[$index-1].score}} 但显然你不能。如果有人对如何解决这个问题有任何想法,将不胜感激!如果我需要提供更多信息,请告诉我。希望这一切都说得通!

谢谢! T

【问题讨论】:

    标签: angularjs angularjs-ng-repeat angular-ngmodel


    【解决方案1】:

    您可以像这样将过滤后的项目分配给名为filteredData 的变量...

    <tr ng-repeat="eachItem in filteredData = (Data |filter: { id: selectedOption.id })">
    

    现在你可以正确使用$index...

    <td>{{ filteredData[$index-1].score }}</td>
    

    要获得真正的运行总计,您实际上需要做更多的事情。一种方法是使用ngInit,虽然我不得不说它在这一点上变得非常老套,但它确实有效......

        <tr ng-repeat="eachItem in filteredData = (Data |filter: { id: selectedOption.id })" 
          ng-init="eachItem.runningTotal = filteredData[$index-1].runningTotal + eachItem.score">
            <td>{{eachItem.day}}</td>
            <td>{{eachItem.score}}</td>
            <td>{{eachItem.score + filteredData[$index-1].runningTotal}}</td>
        </tr>
    

    Live Demo

    也许更好的解决方案是创建一个自定义过滤器,该过滤器输出带有预先计算的运行总计的过滤数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 2023-04-02
      • 1970-01-01
      • 2016-03-04
      • 2014-12-12
      • 2017-02-16
      相关资源
      最近更新 更多