Change src image based on AngularJS ng-click index

I have this angular JS code, the directive template defines:

<li ng-repeat="i in getNum(myNum)" ng-click="toggle($index)" id=$index> <img src="img/{{ImgTest}}"> </li> 

In addition, my directive code has:

 link: function (scope, elem, attrs) { scope.ImgTest= "Img_1"; 

On the ng-click, I want to change the image in all the <li> elements before you click from Img_1 to Img_2. (So ​​change all the <li> elements with an index between 0 and $index one click).

How can this be achieved?
.. Thanks

+6
source share
1 answer

We can use ng-switch , which is controlled by the variable that I call switchPoint , switchPoint set to $index on toggle() ).

Everything before switchPoint will use ImgTest , and everything after using ImgTest2 .

Here's the ng-switch code (which checks the current $index on 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 is an updated link function with a switch function, as well as a 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 the fiddle (which prints {{imgTest}} ... instead of using the image solely for the sake of simplicity): http://jsfiddle.net/ueX3r/

+6
source

Source: https://habr.com/ru/post/959119/


All Articles