2014-05-25 50 views
1

感谢您的阅读/帮助。 我是一个试图找出AngularJS并建立我的第一个应用程序的完全新手。 对于这个项目我创建了一个带有文本框的表格(3行)。数据由Factory填充,每行的总数在控制器中计算。这是所有工作正常(花费我几个小时,但耶!)AngularJS - 如何循环重复项目并进行计算

现在我需要计算在表底部tbTotal文本框中的总和,我现在尝试超过8小时,但不能似乎找到了解决办法。所以我希望有人会帮助。

我试图让事情进入Jsfiddle,但没有发现如何。因此,该项目可以在http://app.novam-it.nl/#/openkassa

发现在http://app.novam-it.nl/app.zip您可以下载projectfiles如果这将是任何帮助

这是我repeatercode:

<tr ng-repeat="type in types"> 
      <td><input ng-change="calc()" type="text" class="form-control" ng-model="type.basic"></td> 
      <td><input type="text" class="form-control" disabled ng-model="type.type" currency></td> 
      <td><input type="text" ng-init="calc()" class="form-control total" disabled ng-model="tbTotal" currency></td> 
     </tr> 

这是我此刻

控制器
app.controller('openKassaController', function(currencyFactory, $scope) { 
$scope.types = currencyFactory.types; 
$scope.calc = function ($scope) { 
    this.tbTotal = this.type.type * this.type.basic; 
}; 

});

我希望有人能帮帮我!

问候,

沃特

+0

没有测试任何这个,似乎你可能想要设置$ scope.tbTotal,而不是this.tbTotal。此外,您应该循环使用您的时间并将它们添加到一起,而不仅仅是硬编码这两个。 –

+0

此时Calc()函数正常工作。有了this.tbTotal,我可以设置每行的tbTotal。我不确定你在循环播放我的时代是什么意思? – Wouter

+0

如果你想摆弄我 – Wouter

回答

2

我分配了一个total功能,每个货币类型的计算为总该类型/行。我也做了一个循环遍历每种类型的$scope.total函数并计算所有行的总数。控制器看起来像这样:

app.controller('openKassaController', function(currencyFactory, $scope) { 
    $scope.types = currencyFactory.types; 
    angular.forEach($scope.types, function(type){ 
     //Add a total function to each row. 
     type.total = function(){ 
     return type.type * type.basic; 
     }; 
    }); 

    //Total for all rows. 
    $scope.total = function(){ 
     var total = 0; 
     angular.forEach($scope.types, function(type){ 
     total += type.total(); 
     }); 
     return total; 
    } 
}); 

我也已经用内置的货币过滤器取代了您的货币指令。

这是plunker显示它的所有工作。

+0

不错,我已经添加了一个zipfile到项目文件。 $ scope.compute是否必要?我没有看到它在任何地方被使用。 – user2847643

+0

糟糕,没有。我已经把它拿出来了。 – Jerrad

+0

谢谢!这解决了我的问题。没有试图弄清楚你到底做了什么。让它成为一个学习的时刻。欢呼 – Wouter

0

如果要计算每行总:

... 
<td><input type="text" ng-init="tbTotal=calc(type)" ... ng-model="tbTotal" currency></td> 

... 
$scope.calc = function (type) { 
    return type.type * type.basic; 
};