简体   繁体   中英

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

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

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