how to get sum inside scope?

how to sum value inside Scope and store to another scope variable ?

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

I want to store the total of sum into $scope.pay

how I can get there?

48 thoughts on “how to get sum inside scope?”

  1. Considering that $scope.cart should be an array you can use Array.prototype.reduce()

    Code example:

    const $scope = {}
    $scope.cart = [{name: 'bag', price: 2000}, {name: 'shoes', price: 3000}]
    $scope.pay = $scope.cart.reduce((a, { price }) => price + a, 0)
    
    console.log($scope.pay)
    Reply
  2. Simple Solution to this is to use parseInt for adding two and storing it in new scope variable.

    Angular JS File:

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

    HTML File:

    <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>
    

    Update 1: BTW. $scope.cart should be array and to access every price, you should use ng-repeat.

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

Leave a Comment