4

当用户单击它时,我正在尝试切换按钮图像。如果可能的话,我更喜欢使用 angularjs 而不是 jquery。现在我有一个工作版本,可以在单击时切换图像,唯一的问题是它会在单击时更改所有图像。如何缩小范围或传入 img 元素的 src 属性?

    <div ng-repeat="merchant in merchants">
      <div class="followrow">
        <a ng-click="toggleImage()"><img id="followbutton" ng-src="{{followBtnImgUrl}}"  /></a>
      </div>
    </div>

app.controller('FollowCtrl', function CouponCtrl($scope) {
    $scope.followBtnImgUrl = '/img1'


    $scope.toggleImage = function () {
        if ($scope.followBtnImgUrl === '/img1.jpg') {
            $scope.followBtnImgUrl = baseUrl + '/img2.jpg';
        } else {
            $scope.followBtnImgUrl = 'img1.jpg';
        }
    }
});

我可以将 img src 属性传递给 toggleImage(this.img.src) 或类似的函数吗?

4

3 回答 3

5
<div ng-repeat="merchant in merchants">
  <div class="followrow">
    <a ng-click="toggleImage(merchant)"><img id="followbutton" ng-src="{{merchant.imgUrl}}"  />
    </a>
  </div>
</div>

.

app.controller('FollowCtrl', function CouponCtrl($scope) {
    $scope.followBtnImgUrl = '/sth.jpg'
    $scope.merchants = [{imgUrl: "img1.jpg", name:"sdf"}, 
                         {imgUrl: "img2.jpg", name: "dfsd"}];


     $scope.toggleImage = function(merchant) {
         if(merchant.imgUrl === $scope.followBtnImgUrl) {
             merchant.imgUrl = merchant.$backupUrl;
         } else {
             merchant.$backupUrl = merchant.imgUrl;
             merchant.imgUrl = $scope.followBtnImgUrl;
         }
    };
});
于 2013-02-15T06:58:20.183 回答
4

您想要的是每个followrow. 正如您的代码所代表的那样,所有followrows 都只引用一个范围。

一个简单的答案是创建一个附加到每个控制器的新控制器followrow

<div class="followrow" ng-controller="ImageToggleCtrl">...</div>

然后将图像切换逻辑移动到该新控制器:

app.controller('ImageToggleCtrl', function($scope) {
  $scope.followBtnImgUrl = '/img1';
  $scope.toggleImage = function() { /* the toggling logic */ };
});

现在,将为每一行实例化一个新范围,并且图像将独立切换。

于 2013-02-14T23:24:05.463 回答
0

我刚刚添加了两个可点击的图像:

<div ng-app="FormApp" ng-controller="myController" max-width="1150px;" width="1150px;" >
    <input ng-show="ShowDown" type="image" style="width:250px; height:40px;" src="~/Content/Images/contactShow.png" ng-click="ShowHide()"/>
    <input ng-show="ShowUp" type="image" style="width:250px; height:40px;" src="~/Content/Images/contactHide.png" ng-click="ShowHide()" />
</div>

他们切换彼此的可见性。在页面加载时,一个可见,一个不可见,两个可点击的图像都调用相同的函数:

<script type="text/javascript">
    var app = angular.module('FormApp', [])
    app.controller('myController', function ($scope) {
        $scope.ShowDown = true;
        $scope.ShowUp = false;

        $scope.ShowHide = function () {
            $scope.ShowDown = $scope.ShowDown ? false : true;
            $scope.ShowUp = $scope.ShowUp ? false : true;
        }
    });
</script>
于 2016-04-04T07:58:21.937 回答