简体   繁体   中英

Angular changing ng-class on click

I am trying to change a class that I am creating based on a value that I get from json, and then change it if user cliks on it, but I am not getting that to work.

This is my code in the controller:

$scope.like = function(){
      if ($scope.class === "ion-ios-heart-outline")
        $scope.class = "ion-heart";
      else
        $scope.class = "ion-ios-heart-outline";
    };

And the element in the view:

<i ng-click="like()" ng-class="{ 'ion-heart' : article.like == 1, 'ion-ios-heart-outline' : article.like == 0}">

You are mixing $scope.class (which is never used in the view) and ng-class , so I am not entirely sure what you want to do. But I guess what you are looking for is this:

$scope.article.like = 0;
$scope.like = function() {
    $scope.article.like = $scope.article.like == 0 ? 1 : 0;
};

Then the CSS classes will be changed based on whether the article was liked or not.

check out this plunker.

https://plnkr.co/edit/1LNxXlDRpzzZImspJJKE?p=preview

$scope.article= {}; 
$scope.article.like = 1;
$scope.like = function()
{
 $scope.article.like = ($scope.article.like === 0 ? 1 : 0);
};

hopefully you are trying to set the class based on the value on article.like in the

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM