我需要一些关于在例如: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");
}
});
谢谢
答案 0 :(得分:0)
您可以使用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>
或者您可以将兴趣转移到您的点击功能并在控制器中设置图像src
<img src="{{interest.iconUrl}}" ng-click="changeImage(interest)">
$scope.changeImage = function(interest){
if(checked)
interest.iconUrl = "active.png";
else
interest.iconUrl = "other.png";
}