Question

Today I faced a strange problem for me in AngularJS.

In this example I have two ng-repeat in product (two or three images and the same number of colors) and one ng-repeat for pagination (irrelevant in this case I assume).

HTML:

<div class="item-wrapper" ng-repeat="item in pagedItems[currentPage]">
  <div class="item">
   <!-- Item image -->
     <div class="item-image">
      <ul>
       <li ng-repeat="desc in item._source.description" ng-show="$first">
        <img class="preview" ng-src="server/{{desc.smallImage.url}}">
       </li>
      </ul>
     </div>
     <!-- Item details -->
    <div class="item-details">
     <div class="product-colors">
      <ul class="btn-group pull-right">
       <li ng-repeat="color in item._source.description">
       <img class="color" ng-src="server/{{color.thumbnailImage.url}}" />
      </li>
     </ul>
    </div>
  </div>
</div>

All I wanted to do is that click on one of colors (img.color) changes corresponding img.preview visibility. In my attempts I was always able to changed every img.preview in whole list, not the one I clicked on.

MY ATTEMPTS:

HTML

<li ng-repeat="desc in item._source.description" ng-show="$index === selectedColor">
<li ng-repeat="color in item._source.description" ng-click="changeColor($index)">

JS (controller)

$scope.changeColor = function(idx) {                
 $scope.selectedColor = idx || 0; //default show always first img.preview from list
};

MY ATTEMPTS #2 (working)

HTML

<li><img class="preview" ng-src="server/{{desc[__selected === $index ? __num : 0].smallImage.url}}">
<li ng-repeat="color in item._source.description" ng-click="changeColor($index, key)">

JS (controller)

$scope.changeColor = function(idx, key) {
  $scope.__selected = key;
  $scope.__num = idx;
};
Was it helpful?

Solution

This might be quite simple:

Considering desc and color will be referring to same object as they are of the same source. So, desc and color should be identical and setting a property on either of them supposed to reflect on the other.

Make the changes as follow and try, havent tested though:

<li ng-repeat="desc in item._source.description" ng-show="item.__selected ? desc==item.__selected : $first">

and

<li ng-repeat="color in item._source.description">
    <img class="color" ng-src="server/{{color.thumbnailImage.url}}" ng-click="item.__selected = color" />
</li>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top