2016-11-07 46 views
0

我想更改类的按钮时点击它,当它的点击逆也找回了昔日的状态再次拨动开关ngclass的onclick与angularjs

$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

在控制器中设置一个标志。并使用它在HTML中使用ng-class例如

回答

0

你“项目'在服务成功后可能没有得到更新。 所以一个方法是添加以下控制器:

$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> 

您需要更新varible名点点。

+0

只是看到你的答案,但我已经更新了脚本。有一个文本必须点击才能开始切换 – user6579134

+0

不错,将角度对象'item'传递到您准备内容的点击函数中,即ng-click =“likepic(item)”。如果这不起作用,那意味着“item”不是有效的对象,请粘贴更多模板,然后查看发生了什么。 – Tushar

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) 
      }); 
    } 
}