AngularJS & JSON – Obtain Value from Previous & Next Object

All we need is an easy explanation of the problem, so here it is.

Background:
I have created an AngularJS test app which, obtains data from a JSON file, which is separated into categories and within each category is an employee card which is displayed through ng-repeat. These categories can then be viewed utilising a slider (using bxSlider).

Aim:
With bxSlider you can use custom Next/Previous buttons, what I wanted to achieve was to dynamically display the relevant category names in the Next/Previous buttons (please see annotation link below – my level does not allow me to post images).

Website Category Slider Wireframe

For example: the current category on view is the ‘Technology’ department, the previous button may then show ‘Motors’ department and the next button may show ‘Law’ department.

I understand that the code below would allow me to access the Category name ‘Technology’. However this needs to be done in a dynamic nature.

{{employees[0].category}}

Below this I will include all what I believe to be relevant code.

JSON file:

[
  {
    "category": "Technology",
    "shortname": "tech",
    "icon": "fa-desktop",
    "cards": [
      {
        "id": "card-1",
        "name": "George Sofroniou",
        "shortname": "G_Sof",
        "age": "23",
        "company": "Pirean Ltd.",
        "role": "Graduate UI Developer"
      },
      {
        "id": "card-2",
        "name": "Steve Jobs",
        "shortname": "S_Jobs",
        "age": "56 (Died)",
        "company": "Apple Inc.",
        "role": "Former CEO"
      },
      {
        "id": "card-3",
        "name": "Mark Zuckerberg",
        "shortname": "M_Zuck",
        "age": "30",
        "company": "Facebook",
        "role": "CEO"
      },
      {
        "id": "card-4",
        "name": "Tim Cook",
        "shortname": "T_Cook",
        "age": "54",
        "company": "Apple Inc.",
        "role": "CEO"
      },
      {
        "id": "card-5",
        "name": "Jony Ive",
        "shortname": "J_Ive",
        "age": "48",
        "company": "Apple Inc.",
        "role": "Senior Vice President of Design"
      },
      {
        "id": "card-6",
        "name": "Marissa Mayer",
        "shortname": "M_May",
        "age": "39",
        "company": "Yahoo!",
        "role": "CEO"
      },
      {
        "id": "card-7",
        "name": "Yves Behar",
        "shortname": "Y_Beh",
        "age": "47",
        "company": "Fuseproject",
        "role": "Founder"
      }
    ]
  },
  {
    "category": "Motors",
    "shortname": "mot",
    "icon": "fa-car",
    "cards": [
      {
        "name": "Elon Musk",
        "shortname": "E_Musk",
        "age": "43",
        "company": "Tesla Motors",
        "role": "CEO"
      }
    ]
  },
  {
    "category": "Football",
    "shortname": "foot",
    "icon": "fa-futbol-o",
    "cards": [
      {
        "id": "card-1",
        "name": "Sir Alex Ferguson",
        "shortname": "A_Fer",
        "age": "73",
        "company": "N/A",
        "role": "Retired"
      }
    ]
  },
  {
    "category": "Law",
    "shortname": "law",
    "icon": "fa-gavel",
    "cards": [
      {
        "id": "card-1",
        "name": "Harvey Specter",
        "shortname": "H_Spec",
        "age": "43",
        "company": "Pearson Specter Litt",
        "role": "Name Partner"
      }
    ]
  }
]

HTML Code:

<!-- Slider Container -->
    <div class="slider-container">
        <!-- Search Content  -->
        <!-- controls: true -->
        <div class="content-results bxslider" 
        bx-slider="mode: 'horizontal', pager: true, nextSelector: '#next', prevSelector: '#prev', nextText: '<i class=\'fa fa-chevron-right\'></i>', prevText: '<i class=\'fa fa-chevron-left\'></i>', minSlides: 1, maxSlides:1, infiniteLoop: true, adaptiveHeight: true, hideControlOnEnd: false">
            <!-- Employee -->
            <div class="cards-container" 
            ng-repeat="item in filtered = ( employees | filter: query | orderBy:empOrder:direction )"
            notify-repeat-finished>
                <div class="category" ng-animate="'animate'" >
                    <div class="category-title">
                        <h1 class="title-cat"><i class="fa {{item.icon}}"></i>&nbsp;{{ item.category }}</h1>
                    </div>
                    <div class="category-cards-container">
                        <div class="employee-card card" ng-repeat="employee in filtered = (item.cards | filter: query | orderBy:empOrder:direction )" dom-manipulation>
                            <!-- Front Card -->
                            <div class="front">
                                <div class="pic-container">
                                    <img ng-src="../static/images/placeholders/{{ employee.shortname }}.jpg" class="emp-pic" alt="Photo of {{ employee.name }}">
                                    <h3 class="emp-name">{{ employee.name }}</h3>
                                <div class="darken"></div>
                                </div>
                                <ul class="emp-details">
                                    <li class="detail emp-age">
                                        <h5>Age: <small>{{ employee.age }}</small></h5>
                                    </li>
                                    <li class="detail emp-role">
                                        <h5>Role: <br><small>{{ employee.role }}</small></h5>
                                    </li>
                                    <li class="detail emp-company">
                                        <h5>Company: <br><small>{{ employee.company }}</small></h5>
                                    </li>
                                </ul>
                            </div>
                            <!-- END Front Card -->
                            <!-- Back Card -->
                            <div class="back">
                                <div id="map-load">
                                    <i class="fa fa-map-marker"></i>
                                </div>
                                <div id="maps-container">
                                    <div id="googleMap"></div>
                                </div>
                                <i class="fa fa-times"></i>
                            </div>
                            <!-- END Back Card -->
                        </div>
                    </div>
                </div>
                <!-- No Matches -->
                <div class="no-match" ng-show="filtered.length == 0">
                    <h3 class="no-matchText">Your search provides no matches!</h3>
                </div>
                <!-- END No Matches -->
            </div>
            <!-- END Employee -->
        </div>
        <!-- END Search Content  -->
        <!-- Next & Previous Buttons -->
        <div class="btn-nextprev">
            <div class="next-container">
                <a href="" class=" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener"btn btn-next" id="next">
                </a>
            </div>
            <div class="prev-container">
                <a href="" class=" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener"btn btn-prev" id="prev">
                </a>
            </div>
        </div>
        <!-- END Next & Previous Buttons -->
    </div>
    <!-- END Slider Container -->

AngularJS:

Controller

var personControllers = angular.module('personControllers', ['ngAnimate']);

//PersonSearch Controller
personControllers.controller('PersonList', ['$scope', '$http', 
function($scope, $http) {

    $http.get('../static/scripts/data2.json').
    success(function(data) {
        console.log("JSON file loaded");
        console.log(data);
        $scope.employees = data;
        //$scope.empOrder = 'name';
    }).
    error(function(){
        console.log("JSON file NOT loaded");
    });

}]);

EDIT
Updated Controller

var personControllers = angular.module('personControllers', ['ngAnimate']);

//PersonSearch Controller
personControllers.controller('PersonList', ['$scope', '$http', 
function($scope, $http) {

    $http.get('../static/scripts/data2.json').
    success(function(data) {
        console.log("JSON file loaded");
        console.log(data);
        $scope.employees = data;
        //$scope.empOrder = 'name';

        //Next & Previous Button Category Label
        $scope.getNextCategoryIndex = function(currentIndex){
            var nextIndex = currentIndex+1;
            if( nextIndex >= $scope.employees.length ){
                //move to start if at list end
                nextIndex = 0;
            }
            return nextIndex;
        }

        $scope.getPrevCategoryIndex = function(currentIndex){
            var prevIndex = currentIndex+1;
            if( prevIndex < 0 ){
                //move to the last index, if already at the start
                prevIndex = $scope.employees.length - 1;
            }
            return prevIndex;
        }

    }).
    error(function(){
        console.log("JSON file NOT loaded");
    });

}]);

Updated Next/Previous Buttons

<!-- Next & Previous Buttons -->
        <div class="btn-nextprev">
            <div class="next-container">
                <a href="" class=" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener"btn btn-next" id="next"> 
                    {{ employees[getNextCategoryIndex($index)].category }}
                </a>
            </div>
            <div class="prev-container">
                <a href="" class=" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener"btn btn-prev" id="prev">
                    {{ employees[getPrevCategoryIndex($index)].category }}
                </a>
            </div>
        </div>
        <!-- END Next & Previous Buttons -->

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I would probably do something like this: create functions to your controller to get the previous and next indexes (to handle the index overflows):

$scope.getNextCategoryIndex = function(currentIndex) {
  var nextIndex = currentIndex+1;
  if (nextIndex >= $scope.employees.length) {
    // move over to start if we already were at the end of the list
    nextIndex = 0;
  }
  return nextIndex;
}

$scope.getPrevCategoryIndex = function(currentIndex) {
  var prevIndex = currentIndex+1;
  if (prevIndex < 0) {
    // move over to the last index, if we already are at the start
    prevIndex = $scope.employees.length - 1;
  }
  return prevIndex;
}

And then in the HTML call those functions using $index (the current index of ng-repeat, see AngularJS documentation for ngRepeat for more details) as parameter:

    <!-- Next & Previous Buttons -->
    <div class="btn-nextprev">
        <div class="next-container">
            <a href="" class=" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener"btn btn-next" id="next">
                {{employees[getNextCategoryIndex($index)].category}}
            </a>
        </div>
        <div class="prev-container">
            <a href="" class=" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener"btn btn-prev" id="prev">
                {{employees[getPrevCategoryIndex($index)].category}}
            </a>
        </div>
    </div>
    <!-- END Next & Previous Buttons -->

Method 2

The code you need should be:

{{employees[$index - 1].category}} //For the prev
{{employees[$index + 1].category}} //For the next

Method 3

Recent Update (09-Apr-2015):

I have now been able to achieve what I wanted, on click of the button the relevant function runs and loops through the category names. One more thing to add now is that the buttons run in sync.

Controller

//Next & Previous Button Category Label
    $scope.i = 0;
    $scope.j = $scope.employees.length;
    $scope.nextCat = $scope.i + 1;
    $scope.prevCat = $scope.j - 1;

    $scope.getNext = function(){
        //console.log($scope.nextCat);
        $scope.nextCat++;
        if( $scope.nextCat >= $scope.employees.length ){
            $scope.nextCat = 0;
        }

        $scope.prevCat++;
        if( $scope.prevCat >= $scope.employees.length ){
            $scope.prevCat = 0;
        }

    };

    $scope.getPrev = function(){
        //console.log($scope.nextCat);
        $scope.prevCat--;
        if( $scope.prevCat < 0 ){
            $scope.prevCat = $scope.employees.length - 1;
        }

        $scope.nextCat--;
        if( $scope.nextCat < 0 ){
            $scope.nextCat = $scope.employees.length - 1;
        }
    };

HTML

<!-- Next & Previous Buttons -->
        <div class="btn-nextprev">
            <div class="next-container">
                <a href="" class=" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener"btn btn-next" id="next" 
                ng-click="getNext()"> 

                </a>
                {{ employees[nextCat].category }}
            </div>
            <div class="prev-container">
                <a href="" class=" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener"btn btn-prev" id="prev"
                ng-click="getPrev()">
                </a>
                {{ employees[prevCat].category }}
                <!-- {{ employees[prevCat].category }} -->
            </div>
        </div>
        <!-- END Next & Previous Buttons -->


Update:
This is still not going to be a viable solution. I am technically able to achieve what is required however I am still required to use position: fixed. This means that the Category label then disappears.

I am now going to try and achieve this without it being within the ng-repeat and using ng-click it will iterate to the next Category name. Hopefully this will be the solution, and I will update upon any success/failure.

Update:

I am yet to find my optimal solution however, my current workaround for this utilises @jmustonen’s solution.

Outside of the bxSlider I have the custom arrow’s (if I placed these inside there were issues with the arrows not duplicating across pages – I believe there’s an issue with it when it has position:fixed).

Then within my ng-repeat I include…

{{ employees[getNextCategoryIndex($index)].category }}

I will then be required to do some CSS in order for this to appear as if it is displayed as part of the Next/Previous buttons. Again these become invisible if position: fixed is used.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply