Marco Marco - 5 months ago 22
AngularJS Question

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}">

str str
Answer

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.

Comments