gpt4 book ai didi

javascript - 在 ng-repeat 上填充新数组

转载 作者:行者123 更新时间:2023-11-28 15:16:17 25 4
gpt4 key购买 nike

$scope Controller 上由代码和金额组成的数组。当计算函数的摘要时,浏览器会出现 Uncaught Error: 10 $digest() iterations reached. Aborting!无限循环引起的错误(奇怪但它正在工作)。

是否有任何正确的方法可以在 ng-repeat 时组合新数组不会出现无限循环错误?

如有任何帮助,我们将不胜感激

jsFiddle Link

更新:线条变量不是静态的,可以添加、修改或删除。 jsFiddle Line for Update

var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.Lines = [ {Code:'X', Amount:'10'},
{Code:'Y', Amount:'10'},
{Code:'Z', Amount:'20'},
{Code:'Y', Amount:'1'}];

$scope.Sums = function(){
var sums = new Array();
for (var i = 0; i < $scope.Lines.length; i++) {
var added = false;
for (var j = 0; j < sums.length; j++) {
if (sums[j].Code == $scope.Lines[i].Code) {
sums[j].Amount = parseFloat( sums[j].Amount) + parseFloat($scope.Lines[i].Amount);
added = true;
break;
}
}
if (!added) {
sums.push( { Code:$scope.Lines[i].Code, Amount: $scope.Lines[i].Amount } );
}
}
return sums;
}
}

HTML:

<div ng-controller="MyCtrl">
<table style="border: 1px solid black;">
<tr ng-repeat="line in Lines">
<td>{{ line.Code }}</td>
<td>{{ line.Amount }}</td>
</tr>
</table>
Summary
<table style="border: 1px solid black;">
<tr ng-repeat="sum in Sums()">
<td>{{ sum.Code }}</td>
<td>{{ sum.Amount }}</td>
</tr>
</table>
</div>

最佳答案

如果您这样做,还会发生这种情况吗:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {

$scope.Lines = [ {Code:'X', Amount:'10'},{Code:'Y', Amount:'10'},
{Code:'Z', Amount:'20'},{Code:'Y', Amount:'1'}];

$scope.Sums = [];
calculate();

var calculate = function(){

$scope.Sums.length = 0;

for (var i = 0; i < $scope.Lines.length; i++) {

var added = false;
for (var j = 0; j < $scope.Sums.length; j++) {

if ($scope.Sums[j].Code == $scope.Lines[i].Code) {
$scope.Sums[j].Amount = parseFloat( $scope.Sums[j].Amount) + parseFloat($scope.Lines[i].Amount);
added = true;
break;
}

}

if (!added) {
$scope.Sums.push( { Code:$scope.Lines[i].Code, Amount: $scope.Lines[i].Amount } );

}

}
}
}

请注意,一旦 Angular 监视 Sums,就永远不要创建新数组,这一点很重要。使用$scope.Sums.length = 0相反,如果您需要清空它。

您认为:<tr ng-repeat="sum in Sums">

关于javascript - 在 ng-repeat 上填充新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33780650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com