javascript - 从 ng-repeat 中求和特定字段值的函数

标签 javascript angularjs

我想创建一个函数来对来自 json 中的 Web 服务的特定属性的值求和。

这是我的功能:

$scope.exportData = data;

$scope.totalLW = function() {
    $scope.total=0;

    for (var i =0; i < $scope.exportData.result.merchMetrics.SALES_AMOUNT_LW.length; i++) {
        $scope.total += parseFloat($scope.exportData.result.merchMetrics.SALES_AMOUNT_LW);
    }

    return $scope.total;
}

在我看来我是这样调用函数的

<td ng-class = "{'positive':totalLW() >= 0, 'negative': totalLW()}">{{totalLW()}}</td>

但是在我看来,我得到了一个undefined,我确定我的函数是错误的,所以我需要一些帮助来找出问题所在。

$scope.exportData 正在工作,因为我有一个表并且绑定(bind)工作正常。

截图。

enter image description here

最佳答案

我看到你忘了在 for 循环中使用数组值。

 $scope.totalLW = function (){
          $scope.total=0;
          for(var i =0; i < $scope.exportData.result.merchMetrics.SALES_AMOUNT_LW.length; i++ ) {

         $scope.total += parseFloat($scope.exportData.result.merchMetrics.SALES_AMOUNT_LW**[i]**);
       }
       return $scope.total;
    }

是的,终于找到了你错过的那一点。你应该遍历
for (var i =0; i <$scope.exportData.result.length; i++)$scope.exportData.result 而不是在 $scope.exportData.result.merchMetrics.SALES_AMOUNT_LW

关于javascript - 从 ng-repeat 中求和特定字段值的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35002356/

相关文章:

javascript - Ajax代码问题

javascript - 使用一个组件在多种状态下使用不同的服务方法

javascript - 更换时 Angular 模型不更新

asp.net - 有没有更好的方法让 ClientID 进入外部 JS 文件?

javascript - 日期倒计时不正确

javascript - html angularjs中的if语句

javascript - 如何设置在 AngularJs 中最初选中的单选按钮?

angularjs - Angular JS $locationChangeStart 获取下一个 url 路由对象

javascript - 对象字面量与模块模式

javascript - 处理相同代码必须立即运行或在 promise 解决后运行的情况的最佳方法