我在data中有一个total函数,但它将结果重复了两次。有人能帮我吗?
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)时,总数会重复两次。我需要使用积分总数来显示图表。
发布于 2017-10-19 06:14:38
您在html中绑定了{{totalCreadit(i.data)}}
,所以每次angular运行摘要循环时都会调用该函数,这可能会经常发生(每个事件),并且angular会为每个事件多次运行它,以确保没有更多的更改。
如果您不想观察(双向绑定)该值,而是只执行一次计算,则必须调用控制器中的函数,然后将结果保存到模型变量中,并仅将结果绑定到视图。
https://stackoverflow.com/questions/46823419
复制相似问题