SaSH_17 SaSH_17 - 4 months ago 26
JSON Question

AngularJS - Loop through several json object arrays

I want to loop through several json object arrays with one ng-click.

Example - Please see following Plunker:
https://plnkr.co/edit/7P4Oha5OdfTC5wndUebE?p=preview

When I click now on one of my blue numbers (anyway which item), it should change to the next one for all items. At the moment, the other item disappears.

So at the end, all items should always have the same number value, when I click on it.

How can I do that ? Thanks for your help...

(function () {
'use strict';

angular
.module('app', [])
.controller('myctrl', myctrl);

function myctrl($scope, $http) {
$http.get("data.json")
.success(function (data) {
$scope.data = data;
$scope.nbr = 0;
});

$scope.next = function (dataId, nbr) {
$scope.nbr = ($scope.nbr + 1) % $scope.data.data[dataId].numbers.length;
};

$scope.change = function (dataId, nbr) {
$scope.data.data[dataId].numbers[nbr].bench = $scope.data.data[dataId].numbers[nbr].number1 +
$scope.data.data[dataId].numbers[nbr].number2 +
$scope.data.data[dataId].numbers[nbr].number3;
}
}
})();

Answer

You problem id that you are trying to change the data object array by using the index of the object.

 $scope.change = function(dataId, nbr) {

        $scope.data.data[dataId].numbers[nbr].bench =     $scope.data.data[dataId].numbers[nbr].number1 + 
                                                          $scope.data.data[dataId].numbers[nbr].number2 +
                                                          $scope.data.data[dataId].numbers[nbr].number3;
     }

When you click any link next() and change() these functions are fired.

next function change the value of nbr from 0 to 1.

change function update the bench property based on index passes and the nbr value.

If you click a link it will pass index 0 or 1(based on first and second link clicked), change function will update only the object which is accessed by this index $scope.data.data[dataId]

Now the problem is that the array is updated for single object but the nbr value is changed for both the link.

since there is no bench property for the other object at other index , it will display blank.

use below code to get it right

 $scope.change = function(dataId, nbr) {


       for(var i = 0; i < $scope.data.data.length; i ++)
       {

        $scope.data.data[i].numbers[nbr].bench =     $scope.data.data[i].numbers[nbr].number1 + 
                                                          $scope.data.data[i].numbers[nbr].number2 +
                                                           $scope.data.data[i].numbers[nbr].number3;
       }
     }

Plunker : https://plnkr.co/edit/fGtpjmbrY5bcmC8VgF5R?p=preview

Comments