目标:有个账单数据,须要盘算这些数据的总和
//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>
能够看到在点击按钮时,总额会及时更新,至此完毕,感谢寓目