我有一个数据总数的函数,但它重复两次结果。有人可以帮帮我吗?
function groupBy(arr, key) {
var newArr = []
, types = {}
, newItem, i, j, cur;
for (i = 0, j = arr.length; i < j; i++) {
cur = arr[i];
if (!(cur[key] in types)) {
types[cur[key]] = {
type: cur[key]
, data: []
};
newArr.push(types[cur[key]]);
}
types[cur[key]].data.push(cur);
}
return newArr;
};
Array.prototype.sum = function (prop) {
var total = 0
for (var i = 0, len = this.length; i < len; i++) {
total += parseInt(this[i][prop])
}
console.log(total);
return total;
}
$scope.totalCreadit = function (st) {
return st.sum("credits");
}
数据
var users = [
{
"creditType": "Transfer"
,"credits": "50"
}, {
"creditType": "Transfer"
,"credits": "50"
}
, {
"creditType": "Bought"
,"credits": "50"
}
, {
"creditType": "Spent"
,"credits": "50"
}
, {
"creditType": "Award"
,"credits": "50"
}
, {
"creditType": "Received"
,"credits": "50"
}];
$scope.items = groupBy(users, "creditType");
完美显示creditType和总数。但是当console.log(总计)总数重复两次时。我需要使用总积分来显示图表。
答案 0 :(得分:3)
你在html中绑定了{{totalCreadit(i.data)}}
,所以每次角度运行一个摘要周期时都会调用该函数,这可能经常发生(每个事件)并且角度为每个事件多次运行,以确保在那里没有更多的变化。
如果您不想观看(双向绑定)此值而是执行此计算一次,则必须在控制器中调用该函数,然后将结果保存到模型变量中,并仅将结果绑定到图。