我想在点击按钮时更改按钮的类别,并在再次点击时反转回原来的状态
$scope.like_btn = "icon ion-ios-heart";
$scope.like_btn2 = "icon ion-ios-heart assertive";
$scope.likepic=function() {
event.preventDefault();
if ($scope.like_btn === "icon ion-ios-heart"){
$scope.like_btn = "icon ion-ios-heart assertive";
$http.post("http://localhost/mywork/scripts/like.php",
{'u_pic_id':$scope.u_pic_id})
.success(function(data){
console.log(data)
});
}
else {
$scope.like_btn = "icon ion-ios-heart assertive";
$scope.like_btn = "icon ion-ios-heart";
$http.post("http://localhost/mywork/scripts/like_delete.php",
{'u_pic_id':$scope.u_pic_id})
.success(function(data){
console.log(data)
});
}
}
HTML
<a href="#" ng-click="likepic()">Click to like</a>
<i ng-class="{ '{{like_btn}}': item.answer==='no liked','{{like_btn2}}':item.answer=='liked' }" ></i> {{item.love_total}} Likes
答案 0 :(得分:0)
您的&#39;项目&#39;服务成功后可能没有更新。 因此,一种方法是向控制器添加以下内容:
$scope.item.isLiked = false; // or initiase it with item.isLiked
$scope.likepic=function(item) {
item.isLiked = item.isLiked;
...
...
}
将角度表达式更改为以下内容:
<i ng-click="likepic(item)" ng-class="{ '{{like_btn}}': item.answer=='no liked','{{like_btn2}}': item.answer=='liked' }" ></i>
您需要稍微更新变量名称。
答案 1 :(得分:0)
在我看你的情况时,onclick的唯一变化是你正在添加'断言'类。以下是方法。
HTML视图中的更改:
<a href="#" ng-click="likepic()">Click to like</a>
<i class="icon ion-ios-heart" ng-class="{'assertive': liked}" ></i> {{item.love_total}} Likes
Javascript中的更改
// Initialize the flag here
$scope.liked = false;
$scope.likepic = function() {
event.preventDefault();
// Toggle the flag here
$scope.liked = !$scope.liked;
// Then perform task as per the new value
// There is some possibility of optimization below too. But since that is not the question, no changes are done here
if ($scope.liked) {
$http.post("http://localhost/mywork/scripts/like.php", { 'u_pic_id': $scope.u_pic_id })
.success(function(data) {
console.log(data)
});
} else {
$http.post("http://localhost/mywork/scripts/like_delete.php", { 'u_pic_id': $scope.u_pic_id })
.success(function(data) {
console.log(data)
});
}
}