locked
angular: plus numbers from json file RRS feed

  • Question

  • User-910579361 posted

    hello

    I need some help here..

    i have this json file:

    {
    "col": [
         {
              "rec": {
                   "id":"0001",
                   "name":"name1",
                   "loc": [
                        {"name":"cal", "nb":350},     <--- i want this number
                        {"name": "fat", "nb":100}]
              }
         },
         {
              "rec": {
                   "id":"0002",
                   "name": "name2",
                   "loc": [
                        {"name":"cal", "nb":650},     <--- i want this number
                        {"name": "fat", "nb":100}]
              }
         }
    ]}


    I want to plus all the cal - nb numbers from my json file.
    like this: 350 + 650 = 1000

    i have this function. but i can not get this to work correctly. my totalcount just stay at 0 all the time.

    app.controller('appCtrl', function($scope) {
       
        $scope.totalCount = function() {
    
            var count = 0;
            angular.forEach($scope.data, function(value, key) {
                 count = count + value.col.rec.loc[0].nb;
            });
            return count;
        }
    
    });


    can someone help me make this work?  thanks :-)

    Monday, November 23, 2015 11:09 AM

Answers

  • User61956409 posted

    Hi kkooaa,

    The following sample code works fine on my side, please refer to it.

    <input data-ng-click="totalCount()" type="button" value="click me" />
    $scope.totalCount = function () {
        var count = 0;
        for (var i = 0; i < $scope.data.col.length; i++) {
            count = count + $scope.data.col[i].rec.loc[0].nb;
        }
        alert(count);
        //return count;
    
    }
    

    Best Regards,

    Fei Han



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, November 24, 2015 2:56 AM