Developer
Developer

Reputation: 47

Navigate through a JSON model on click on a link with AngularJS

i want to realize a library in AngularJS with Dropdowns to choose a book and than the chapter of the book. After the slection of a chapter the choosen chapter text appears. All books are in one JSON format. How could I navigate to the next chapter with the link in the bottom left corner (see picture)?

Picture: First i choose a Book and than the chapter dropdown appears

// index.html
<div ng-controller="ArticlesCtrl">
   <br/>
   <div class="dropdown">
      <form class="form" name="myForm">
         <label for="mySelect">Choose a Book:</label>
         <select class="dropdown-select" name="mySelect" id="mySelect" ng-options="option.bname for option in articles" ng-model="articles.bname" ng-change="updateBook()"></select>
      </form>
   </div>
   <div class="dropdown">
      <form class="form" name="myForm" ng-show="chapters" class="ng-hide">
         <label for="mySelect">Choose a chapter:</label>
         <select class="dropdown-select" name="mySelect" id="chapter" ng-options="option.Icnumber for option in selected" ng-model="selected.Icnumber" ng-change="updateChapter()"></select>
      </form> 
   </div>

   <hr>

   <p ng-repeat="paragraph in paragraphs track by paragraph.Ivnumber">{{paragraph.Ivnumber}} {{paragraph.Itext}}"</p>

   <a>Next Chapter</a>

</div> 

app.js

.controller('ArticlesCtrl', function($scope, $location, $http, Cart){
$scope.cart = Cart;
$http.get('lib.json').then(function(articlesResponse) {
  $scope.articles = articlesResponse.data;
  $scope.chapters = false;
  $scope.paragraph = false;
  $scope.show = false;
  $scope.updateBook = function() {
    var Item = $scope.articles.bname.Ibnumber;
    var indexItem = Item - 1;
    $scope.selected = articlesResponse.data[indexItem].CHAPTER;
    $scope.chapters = true;
  }
  $scope.updateChapter = function() {
    var Item = $scope.articles.bname.Ibnumber;
    var indexItem = Item - 1;  
    var Chapter = $scope.selected.Icnumber.Icnumber;
    var indexChapter = Chapter - 1;
    $scope.paragraphs = articlesResponse.data[indexItem].CHAPTER[indexChapter].PARAGRAPH;
    $scope.paragraph = true;
  }
});
})

Thanks

Upvotes: 3

Views: 77

Answers (1)

Shanavas M
Shanavas M

Reputation: 1629

You can just try this. Make the updateChapter function generic.

<a ng-click="updateChapter(selected.Icnumber + 1)">Next Chapter</a>

Change updateChapter function accordingly

$scope.updateChapter = function(chapter) {
    var Item = $scope.articles.bname.Ibnumber;
    var indexItem = Item - 1;
    //update the select menu
    $scope.selected.Icnumber = chapter;
    var indexChapter = chapter - 1;
    $scope.paragraphs = articlesResponse.data[indexItem].CHAPTER[indexChapter].PARAGRAPH;
    $scope.paragraph = true;
}

and the ng-change="updateChapter()" to ng-change=updateChapter(selected.Icnumber)"

Upvotes: 1

Related Questions