作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
$scope
Controller 上由代码和金额组成的数组。当计算函数的摘要时,浏览器会出现 Uncaught Error: 10 $digest() iterations reached. Aborting!
无限循环引起的错误(奇怪但它正在工作)。
是否有任何正确的方法可以在 ng-repeat
时组合新数组不会出现无限循环错误?
如有任何帮助,我们将不胜感激
更新:线条变量不是静态的,可以添加、修改或删除。 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/
我是一名优秀的程序员,十分优秀!