.directive('checkout',['Cart', function(Cart) {
return {
restrict: 'A',
template: '<div data-ng-repeat="item in items">' +
'<div class="clearfix item-box">'+
'<div class="col-md-2 text-left item-pic"><img class="img-responsive img-rounded" alt="{{item.title}}" data-ng-src="/public/upload/{{item.pic}}"></div>'+
'<div class="col-md-2 text-left item-quantity">{{item.quantity}}</div>'+
'<div class="col-md-4 text-left item-title">{{item.title}}</div>'+
'<div class="col-md-4 text-right item-subtot">{{item.price * item.quantity}}</div>'+
'</div>'+
'</div>'+
'<div class="text-right">Tot: {{tot}}</div>',
controller: function($scope,$element) {
$scope.items = Cart.get();
$scope.tot = _.reduce( $scope.items, function(sum, item) {
return sum + (item.price * item.quantity);
},0);
}
};
}]);
有没有办法直接在模板中进行求和 还是更好的方式?
答案 0 :(得分:0)
这个怎么样?
.directive('checkout',['Cart', function(Cart) {
return {
restrict: 'A',
template: '<div data-ng-repeat="item in items">' +
'<div class="clearfix item-box">'+
'<div class="col-md-2 text-left item-pic"><img class="img-responsive img-rounded" alt="{{item.title}}" data-ng-src="/public/upload/{{item.pic}}"></div>'+
'<div class="col-md-2 text-left item-quantity">{{item.quantity}}</div>'+
'<div class="col-md-4 text-left item-title">{{item.title}}</div>'+
'<div class="col-md-4 text-right item-subtot">{{item.price * item.quantity}}</div>'+
'<div class="col-md-4 text-right item-subtot" ng-show="false">{{total = total + item.price * item.quantity}}</div>'+
'</div>'+
'</div>'+
'<div class="text-right">Tot: {{total}}</div>',
controller: function($scope,$element) {
$scope.total = 0;
$scope.items = Cart.get();
}
};
}]);
答案 1 :(得分:0)
就像我在评论中提到的那样,您可以使用ng-init
。
在进行ng-repeat之前,您需要添加ng-init="tot=0"
。然后,在每个ng-repeat
内,您需要添加ng-init=$parent.total = $parent.total + (item.price * item.quantity)
。
这是 Demo