根据 ng-click 索引 AngularJS 更改图像 src [英] Change image src based on ng-click index AngularJS

查看:22
本文介绍了根据 ng-click 索引 AngularJS 更改图像 src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 angularJS 代码,指令模板定义:

  • <img src="img/{{ImgTest}}">
  • 另外,我的指令代码有:

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

    在一次 ng-click 中,我希望在从 Img_1 单击到 Img_2 之前更改所有

  • 元素上的图像.(因此,更改所有
  • 元素,其索引介于 0 和单击的 $index 之间).

    如何实现?
    ...谢谢

    解决方案

    我们可以使用一个 ng-switch,它由我调用的变量 switchPoint 控制,switchPointtoggle() 设置为 $index.

    switchPoint 之前的所有内容都将使用 ImgTest 而之后的所有内容都将使用 ImgTest2.

    这是 ng-switch 代码(它根据 switchPoint 测试当前的 $index).

    <div ng-switch-when=true><img src="img/{{ImgTest}}">

    <div ng-switch-when=false><img src="img/{{ImgTest2}}">

  • 这是一个带有切换函数和 switchPoint 变量的更新链接函数.

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

    这是一个小提琴(打印 {{imgTest}}... 而不是纯粹为了简单起见使用图像):http://jsfiddle.net/ueX3r/

    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

    解决方案

    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/

    这篇关于根据 ng-click 索引 AngularJS 更改图像 src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    其他开发最新文章
    热门教程
    热门工具
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆