Change image src based on ng-click index AngularJS

五迷三道 提交于 2019-12-06 01:12:36

问题


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


回答1:


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/



来源:https://stackoverflow.com/questions/20312922/change-image-src-based-on-ng-click-index-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!