oderfla oderfla - 3 months ago 19
AngularJS Question

Selecting multiple images in Ionic

I have this html:

<div ng-repeat="image in images">
<img ng-src="img/{{image}}_off.png" />
</div>


And this javascript in the controller:

$scope.images = ['imga','imgb','imgc'];


I also have these image files:

imga_off
imga_on
imgb_off
imgb_on
imgc_off
imgc_on


What I need is to switch between on and off when an image is clicked.

Im not really sure what the best approach is.
Is it about attaching an ng-model for each img-element?
Or is there any better way to do this?

Answer

Hold toggle data in $scope variable:

var $scope.toggles = [false, false, false];

Toggle based on $index:

<div ng-repeat="image in images">
  <img ng-src="img/{{image}}_{{ toggles[$index] ? 'on' : 'off' }}.png" ng-click="toggles[$index] = !toggles[$index]"/>
</div>

Note: This code is untested but this is a general approach. You could also hold toggle data as part of $scope.images