更新:我得到产品和总成本的总和,但数量更新时没有更新



我得到了产品和所有成本的总和,但我想在产品数量变化时更新

.filter('total', function () {
    return function (input, property) {
        var i = input instanceof Array ? input.length : 0;
        if (typeof property === 'undefined' || i === 0) {
            return i;
        } else if (isNaN(input[0][property])) {
            throw 'filter total can count only numeric values';
        } else {
            var total = 0;
            while (i--)
                total += input[i][property];
            return total;
        }
    };
})

<div>{{ data|total }} items</div>
            <div>{{ data|total:'price' }}</div>

演示为更新恰好

最后我在angularjs中使用过滤器得到了它…

//code for getting total number of products
    .filter('total', function () {
        return function (input, property) {
            var i = input instanceof Array ? input.length : 0;
            if (typeof property === 'undefined' || i === 0) {
                return i;
            } else if (isNaN(input[0][property])) {
                throw 'filter total can count only numeric values';
            } else {
                var total = 0;
                while (i--)
                    total += input[i][property];
                return total;
            }
        };
    })

//to print the total
     <div>{{ data|total }} items</div>

//to get the overall cost when you update item in quantity
 $scope.total = function () {
        var total = 0;
        angular.forEach($scope.data, function (item) {
            total += item.quan * item.price;
        })
        return total;
    }

// to print the overall total
<div>new total{{total()}}</div>

更新的Plunker Demo

您的产品似乎存储在$scope.todos中,因为这是您在ng-repeat中迭代的内容。但是计算$scope.item的总迭代次数的循环。

应该是

angular.forEach($scope.todos, function (item) {

尝试使用

Change  total to total: {{ getTotal() }} in your template
控制器

$scope.getTotal = function () {
    var total = 0;
    for(var i = 0; i < $scope.cart.items.length; i++){
       var item = $scope.cart.items[i];
       total += (item.price * item.quantity);
    }
    return total;
}
.filter('total', ['$parse', function ($parse) {
    return function (input, property) {
    var i = input instanceof Array ? input.length : 0,
        p = $parse(property);
    if (typeof property === 'undefined' || i === 0) {
        return i;
    } else if (isNaN(p(input[0]))) {
        throw 'filter total can count only numeric values';
    } else {
        var total = 0;
        while (i--)
            total += p(input[i]);
        return total;
    }
};
}]);

最新更新