Change image src based on ng-click index AngularJS

angularjs, angularjs-directive

Solution

We can use an `ng-switch` that is controlled by a variable I'm calling `switchPoint`, `switchPoint` is set to `$index` by `toggle()`).

Everything before `switchPoint` will use `ImgTest` while everything after will use `ImgTest2`.

Here's the `ng-switch` code (which tests the current `$index` against `switchPoint`).

<div ng-switch="switchPoint < $index">
    <div ng-switch-when=true>
        <img src="img/{{ImgTest}}">
    </div>
    <div ng-switch-when=false>
         <img src="img/{{ImgTest2}}">
    </div>
</div>

Here's an updated link function with the toggle function, and `switchPoint` variable.

link: function (scope, elem, attrs) {            
     scope.ImgTest= "Img_1";
     scope.ImgTest2= "Img_2";
     scope.switchPoint = -1;
     scope.toggle= function(val) {
        scope.switchPoint= val;
    };
}

Here's a fiddle (that prints {{imgTest}}... instead of using an image purely for simplicity sake): http://jsfiddle.net/ueX3r/

Problem

I have this angularJS code, the directive template defines: ``` <li ng-repeat="i in getNum(myNum)" ng-click="toggle($index)" id=$index> <img src="img/{{ImgTest}}"> </li> ``` Also, my directive code has : ``` link: function (scope, elem, attrs) { scope.ImgTest= "Img_1"; ``` On an ng-click I wish to change the image on all the `<li>` elements before the one clicked from Img_1 to Img_2. (So change all the `<li>` elements with an index between 0 and the `$index` of the one clicked). How can this be achieved ? .. Thanks

Original source