如何获得范围内的总和?

时间:2019-07-08 07:23:23

标签: javascript angularjs

如何求和范围内的值并存储到另一个范围变量?

$scope.cart = {
   { name: bag , price : 2000 },
   { name: shoes, price : 3000}
}

我想将总和存储到$ scope.pay

我怎么到达那里?

3 个答案:

答案 0 :(得分:0)

考虑到$scope.cart应该是array,您可以使用Array.prototype.reduce()

$scope.cart = [{name: 'bag',price: 2000},{name: 'shoes',price: 3000}];
$scope.pay = $scope.cart.reduce((a, c) => c.price + a.price);

代码示例:

const $scope = {};
$scope.cart = [{name: 'bag',price: 2000},{name: 'shoes',price: 3000}];
$scope.pay = $scope.cart.reduce((a, c) => c.price + a.price);

console.log($scope.pay);

答案 1 :(得分:0)

$scope.cart = [
 { name: 'bag' , price : 2000 },
 { name: 'shoes', price : 3000}
];

$scope.pay = $scope.cart.reduce((accumulator, currentValue) => accumulator.price + currentValue.price);

购物车必须是一个数组。使用reduce函数来获取总和。更多信息在这里-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

答案 2 :(得分:0)

一个简单的解决方案是使用parseInt添加两个并将其存储在新的范围变量中。

Angular JS文件:

var myApp = angular.module('myApp', []);
myApp.controller("myCtrl", function ($scope) {
    $scope.sum = function (price1, price2) {
        $scope.pay = parseInt(price1) + parseInt(price2);
    }
});

HTML文件:

<body>
    <div ng-app = "myApp" ng-controller = "myCtrl">
        Enter First Number:<input type = "text" ng-model = "price1" />
        <br />
        Enter Second Number:<input type = "text" ng-model = "price2" />
        <br />
        <input type = "button" value = "Add" ng-click = "sum(price1, price2)" />
        Total : pay <input type = "text" ng-model = "pay" />
    </div>
</body>

更新1:。 $ scope.cart应该是数组,并且要使用每个价格,您应该使用ng-repeat。

$scope.cart = [
    {name:'bag', price : 2000},
    {name:'shoes', price : 3000}
    ];