2014-12-02 89 views
3

我是AngularJS的新手。 我正在尝试创建一个简单的Web应用程序,它不过是显示产品的页面。当用户点击下一个时,他们被带到阵列中的下一个产品。获取ngClick上的下一个项目

目前我能使用ngRepeat指令来显示阵列中的所有项目:

<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' }, 
    ]; 

})(); 

但我真正想要的是有一个简单的“下一个“按钮,该按钮将在阵列中的下一个所有产品信息中填充同一页面。

+1

我们可以如何帮助您? – cbass 2014-12-02 21:31:36

+0

我希望该页面能够与数组中的下一个产品一起填充,但我不知道如何做到这一点。 – GeeJay 2014-12-02 21:37:21

回答

1

我删除了ng-repeat,只显示一个项目,并将store.nextProductstore.prevProduct添加到您的按钮以选择下一个或上一个项目。

<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> 

在控制器我实现了next和prev函数和存储的索引来跟踪当前显示视图中的哪些项目。

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' }, 
]; 

Here's a working "fiddler".