Reputation: 141
I'm really new to AngularJS. I'm trying to create a simple web app that is nothing more than a page that displays a product. When the user clicks next they are taken to the next product in the array.
At the moment I'm able to use the ngRepeat directive to show all items 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 what I really want is to have a simple "next" button that will populate the same page with all of the product information next in the array.
Upvotes: 4
Views: 3047
Reputation: 2558
I removed the ng-repeat to only show one item at the time and added store.nextProduct
and store.prevProduct
to your buttons to choose next or previous item.
<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 prev functions and stored an index to keep track of what item that is currently displaying 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' },
];
Upvotes: 2