6

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

3
  • Right now every <li> will get the same image- Img_1. Do you want them all to change on the ng-click? Or do you want just the image in that one <li> to change? Or? Commented Dec 1, 2013 at 19:18
  • Thanks Dave for replying.. I want the image from start of the list to that list element to change Commented Dec 1, 2013 at 19:20
  • i.e. from first element of the list to that index... Any help would be highly appreciated... really stuck in here Commented Dec 1, 2013 at 19:30

1 Answer 1

6

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.