SaSH_17 SaSH_17 - 1 year ago 75
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:

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

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

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

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

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

Answer Source

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

        $[dataId].numbers[nbr].bench =     $[dataId].numbers[nbr].number1 + 
                                                          $[dataId].numbers[nbr].number2 +

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 $[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 < $; i ++)

        $[i].numbers[nbr].bench =     $[i].numbers[nbr].number1 + 
                                                          $[i].numbers[nbr].number2 +

Plunker :