【问题标题】:AngularJS toggle ng source value on clickAngularJS在点击时切换ng源值
【发布时间】:2018-02-01 05:30:40
【问题描述】:

我需要一些关于在例如 image.jpg 和 image-active.jpg 之间切换 ng-src 的帮助,但是我有一些问题,因为我需要使用 AngularJS 来激活它。

这是场景:我从 swagger 中调用了一个 API 数据并使用 ng-repeat 以 html 显示图像。

HTML

<div class="input-group interests-list">
     <div class="checkbox" ng-repeat="interest in interests">
         <label>
             <div class="interest-icon">
                 <img src="{{interest.iconUrl}}" ng-click="changeImage()">
              </div>
              <input style="display: none;" type="checkbox" value="{{interest.name}}">
                                {{interest.name}}
         </label>
      </div>
</div>

服务

this.getInterests = function () {

    var deferred = $q.defer();

    var req = {
        method: 'get',
        url: 'http://customdealwebapi20180125110644.azurewebsites.net/api/Interests'
    }

    $http(req).then(function (response) {
        deferred.resolve(response.data);
    }, function (err) {
        console.log(err)
    });

    return deferred.promise;
}

控制器

      TestService.getInterests().then(function (data) {
        $scope.interests = data;
    });

一切正常

现在我想实现当有人点击图片时,ng-src应该改成image-active.jpg,下次点击图片应该改成默认值(image.jpg)

我知道如何通过jQuery来实现,像这样

$(".interests-list .checkbox label input[type='checkbox']").change(function () {
      var selectedIcon = $(this).val();

      if (this.checked) {
          console.log($(this).prev())
        $(this).prev().find("img").attr("src", "assets/img/home/icons/" + selectedIcon + "-active.png");
      } else {
        $(this).prev().find("img").attr("src", "assets/img/home/icons/" + selectedIcon + ".png");
      }
    });

谢谢

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    你可以使用 ng-show

     <div class="checkbox" ng-repeat="interest in interests" ng-init="interest.active = false">
         <label>
             <div class="interest-icon">
                 <img ng-show="interest.active == true" src="active.png" ng-click="interest.active = !interest.active">
                 <img ng-show="interest.active == false" src="other.png" ng-click="interest.active = !interest.active">
              </div>
         </label>
      </div>
    

    或者您可以将兴趣传递给您的点击功能并在您的控制器中设置图像源

    <img src="{{interest.iconUrl}}" ng-click="changeImage(interest)">
    
    $scope.changeImage = function(interest){
    
        if(checked)
            interest.iconUrl = "active.png";
        else
            interest.iconUrl = "other.png";
        }
    

    【讨论】:

    • 你能分享一些关于你的答案的小提琴吗?不适合我
    • 如果你用你的基本代码添加一个工作小提琴,我很乐意更新你的小提琴我的建议。
    • 很高兴能帮上忙。
    猜你喜欢
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 1970-01-01
    • 2015-09-26
    相关资源
    最近更新 更多