目的:有个账单数据,需要计算这些数据的总和
//index.js
function MainController($scope) {
var vm = this;
vm.sum = 0;
vm.items = [
{
name: '早餐',
money: 4
},
{
name: '午餐',
money: 13
},
{
name: '晚餐',
money: 13
}
];
vm.addItem = addItem;
for (var i = vm.items.length - 1; i >= 0; i--) {
vm.sum += parseInt(vm.items[i]['money']);
}
function addItem() {
var item = {
name: '零食',
money: 5
};
vm.items.push(item);
}
return vm;
}
// index.html
<div data-ng-controller="MainController as vm">
<p>{{ sum }}</p>
<div data-ng-repeat="item in vm.items">
<span>{{ item.name }}</span>
<span>{{ item.money }}</span>
</div>
<button data-ng-click="vm.addItem()">新增支出</button>
</div>
只有在页面刷新时,才能见到正确的账单总额,但当我点击按钮添加新支出时,页面的总额却没有更新,即便我使用$watch也无效,代码如下:
$scope.$watch('vm.items', function() {
for (var i = vm.items.length - 1; i >= 0; i--) {
vm.sum += parseInt(vm.items[i]['money']);
}
});
调试可以发现,在页面刷新的时候,会进入计算得到sum,但是当我添加新支出时,是不会进入计算sum的,原因我不得而知,且不论我写的是否规范正确,如果你知道原因的,可以告诉我吗,谢谢。
我上网搜索的过程,发现了在我看来是比较优雅(装逼)的做法,就是使用filter,代码如下:
//index.js
angular.module('deapp', [])
.controller('MainController', ['$scope', MainController]);
function MainController($scope) {
var vm = this;
vm.items = [
{
name: '早餐',
money: 4
},
{
name: '午餐',
money: 13
},
{
name: '晚餐',
money: 13
}
];
vm.addItem = addItem;
function addItem() {
var item = {
name: '零食',
money: 5
};
vm.items.push(item);
}
return vm;
}
//filter.js
angular.module('deapp')
.filter('sumOfItems', sumOfItems);
function sumOfItems() {
return function(data, key){
if(typeof(data) === undefined || typeof(key) === undefined ) {
return 0;
}
var sum = 0,
i = data.length - 1;
for(; i >= 0; i--) {
sum += parseInt(data[i][key]);
}
return sum;
};
}
//index.html
<!DOCTYPE html>
<html lang="zh-hans-mn" data-ng-app="deapp">
<head>
<meta charset="UTF-8">
<title>angularjs filter</title>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script src="index.js"></script>
<script src="filters.js"></script>
</head>
<body>
<div data-ng-controller="MainController as vm">
<p>总额:{{ vm.items | sumOfItems:'money' }}</p>
<div data-ng-repeat="item in vm.items">
<span>{{ item.name }}</span>
<span>{{ item.money }}</span>
</div>
<button data-ng-click="vm.addItem()">新增支出</button>
</div>
</body>
</html>
可以看到在点击按钮时,总额会实时更新,至此结束,谢谢观看