Get next element in an array on ngClick
I am really new to AngularJS. I am trying to create a simple web application that is nothing more than a page displaying a product. When the user clicks the Next button, they move on to the next product in the array.
Currently I can use the ngRepeat directive to display all the elements in the array:
<body class="container" ng-controller="StoreController as store">
<center><div ng-repeat="product in store.products">
<img width="200" ng-src="{{product.images}}"/>
<h4>{{product.item}}</h4>
<h4>Amount: {{product.number}} count: {{count}}</h4>
<button ng-click="count = count + 1" ng-init="count=0">
Increase
</button>
<br>
<button ng-click="count = count - 1" ng-init="count=0">
Decrease
</button>
<br><br>
</h3>
<button class="button" >Add</button>
</div>
</center>
(function() {
var app = angular.module('store', [ ]);
app.controller('StoreController', function(){
this.products = items;
});
var items = [
{ item: 'Top', number: 2, images: 'shirt_icon.jpeg' },
{ item: 'Bottom', number: 5, images: 'pants_icon.jpg' },
{ item: 'Underwear', number: 3, images: 'underwear_icon.jpg' },
];
})();
But I really want to have a simple Next button that will populate the same page with all the product information next in the array.
source to share
I removed ng-repeat to only display one element and added store.nextProduct
also store.prevProduct
to your buttons to select the next or previous element.
<body class="container" ng-controller="StoreController as store">
<center>
<img width="200" ng-src="{{store.currentProduct.images}}"/>
<h4>{{store.currentProduct.item}}</h4>
<h4>Amount: {{store.currentProduct.number}}</h4>
<button ng-click="store.nextProduct()">
Increase
</button>
<br>
<button ng-click="store.prevProduct()">
Decrease
</button>
<br><br>
<button class="button">Add</button>
</center>
</body>
In the controller, I implemented the next and previous functionality and kept an index to keep track of which item is currently displayed in the view.
var app = angular.module('store', []);
app.controller('StoreController', function(){
var productIndex = 0;
this.currentProduct = items[productIndex];
this.nextProduct = function() {
productIndex = productIndex+1;
this.currentProduct = items[productIndex];
};
this.prevProduct = function() {
productIndex = productIndex-1;
this.currentProduct = items[productIndex];
};
});
var items = [
{ item: 'Top', number: 2, images: 'shirt_icon.jpeg' },
{ item: 'Bottom', number: 5, images: 'pants_icon.jpg' },
{ item: 'Underwear', number: 3, images: 'underwear_icon.jpg' },
];
source to share