amir hanif
amir hanif

Reputation: 129

How to add a active class on ng-click buttons?

This is the html code for the buttons, taskfilter is the filter of how the buttons work on click and the class name is 'sel'

<a class="clear-completed" ng-click="taskfilter = 1" ng-class="{'sel':enabled}">
  <span>show completed</span>.
</a>
<a class="clear-completed" ng-click="taskfilter = 2" ng-class="{'sel':enabled}">
  <span>show to do</span>.
</a>
<a class="clear-completed" ng-click="taskfilter = 0" ng-class="{'sel':enabled}">
  <span>show all</span>.
</a>  

This is the code I used to add the class scope with the button on click removed the index in html because it wont work

$scope.taskfilters = 0;
$scope.taskfilter = function(index) {
    $scope.taskfilters = index;
};

Upvotes: 2

Views: 1187

Answers (4)

Manikandan Velayutham
Manikandan Velayutham

Reputation: 2228

<a class="clear-completed" ng-click="taskfilters = 1" ng-class="{'sel':taskfilters == 1}">
     <span>show completed</span>.
</a>
<a class="clear-completed" ng-click="taskfilters = 2" ng-class="{'sel':taskfilters} == 2">
     <span>show to do</span>.
</a>
<a class="clear-completed" ng-click="taskfilters = 0" ng-class="{'text-primary':!taskfilters, 'sel':taskfilters == 0}">
     <span>show all</span>.
</a>

Upvotes: 1

Ankit Vadi
Ankit Vadi

Reputation: 475

<a class="clear-completed" ng-click="taskfilters = 1" ng-class="{'sel':taskfilters == 1}">
     <span>show completed</span>.
</a>
<a class="clear-completed" ng-click="taskfilters = 2" ng-class="{'sel':taskfilters} == 2">
     <span>show to do</span>.
</a>
<a class="clear-completed" ng-init="taskfilters = 0" ng-click="taskfilters = 0" ng-class="{'sel':taskfilters == 0}">
     <span>show all</span>.
</a>

Upvotes: 1

Coder
Coder

Reputation: 339

var app = angular.module("ap",[]);

app.controller("con",function($scope) {

$scope.class = "red";
$scope.changeClass = function(){
if ($scope.class === "red")
  $scope.class = "blue";
else
  $scope.class = "red";
};

});

.red{
 color:red;
 }

  .blue{
  color:blue;
 }

Upvotes: 0

Satpal
Satpal

Reputation: 133403

You can use ngClass directive

If the expression evaluates to an object, then for each key-value pair of the object with a truthy value the corresponding key is used as a class name.

<a ng-class="{'active' : taskfilter == 0}" ng-click="taskfilter = 0">

Upvotes: 1

Related Questions