如何为ng-click设置ng重复项目的索引?

时间:2014-08-27 16:32:06

标签: angularjs angularjs-directive angularjs-ng-repeat

我有一个带缩略图的图库图片。当我点击缩略图时,我希望主图像用它的完整图像显示缩略图索引。如何添加ng-click以获取当前索引?

  <div ng-controller="GalleryController as gallery">
                <img ng-src="{{product.images[gallery.current]}}" />
                <div>
                    <img ng-src="{{image.thumb}}" ng-repeat="image in product.images" ng-click="gallery.setCurrent(image[i])" />
                </div>
            </div>

       app.controller('GalleryController', function () {
            this.current = 0;

            this.setCurrent = function (val) {
                this.current = val;
            }

        });

     var gems = [
         {
           images: [
                 {
                     full: 'img/diamond.jpg',
                     thumb: 'img/diamond.jpg'
                 },
                    {
                        full: 'img/diamond2.jpg',
                        thumb: 'img/diamond2.jpg'
                    }

             ]},

        ];

1 个答案:

答案 0 :(得分:2)

只需传递image对象本身或使用$index(ng-repeat将此属性放在其范围内),该属性将具有当前迭代项的索引。

传递当前图像项目: -

<img ... ng-repeat="image in product.images" ng-click="gallery.setCurrent(image)" />

或传递该项目的索引: -

<img ... ng-repeat="image in product.images" ng-click="gallery.setCurrent($index)" />