RudziankoŇ≠ RudziankoŇ≠ - 3 months ago 16
AngularJS Question

AngularJS: Iterate over array by clicking button

Sorry for dump, question, I am new to

AngularJS
and to
JavaScript
. I would like to iterate over collection by clicking the button.

<body ng-init="customers = [
{'name':'John', 'city':'Doe'},
{'name':'Anna', 'city':'Smith'},
{'name':'Peter', 'city':'Jones'}
]">


<div class="container" ng-app="myApp" ng-controller="myCtrl" >
<div class="span12">
<h1>{{name}}</h1>
<br/>
<p>{{city}}</p>


<button type="button" name="button" value="Next" ng-click="makeIterator($scope.customers)"></button>
</div>
</div>


So after clicking
Next
button I would like to see next iteration of customers displayed. How could I make it?

Answer

You can store an index and increment it when clicking on the button

<body ng-app="myApp">
<div class="container" ng-controller="myCtrl" >
   <div class="span12">
      <h1>{{customers[currentCustomerIdx].name}}</h1>
      <br/>
      <p>{{customers[currentCustomerIdx].city}}</p>


  <button type="button" name="button" value="Next" 
          ng-click="index = (index + 1) % customers.length"></button>
</div>

<script>
 angular.module('myApp', [])
 .controller('myCtrl', function ($scope) {
    $scope.customers = [
     {'name':'John', 'city':'Doe'},
     {'name':'Anna', 'city':'Smith'},
     {'name':'Peter', 'city':'Jones'}];
    $scope.currentCustomerIdx = 0;
  });
</script> 
Comments