当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to add a class to an element and remove to the others siblings in AngularJS

问题描述:

I have a list of li elements which are a sidebar. I'm looking the way to add a class active to the one clicked, and remove that class from the others.

This is my html code:

...

<li ng-click="openNav($event)" ng-class="{'active': isActive }">

...

</li>

<li ng-click="openNav($event)" ng-class="{'active': isActive }">

...

</li>

<li ng-click="openNav($event)" ng-class="{'active': isActive }">

...

</li>

And this is the code on my controller

Test.controller('NavController', function($scope, $http) {

$scope.isActive = false;

$scope.openNav = function($event) {

//$scope.isActive = true;

}

})

The line $scope.isActive = false; removes the class as I need, but I cannot find the way to add the class to the clicked

网友答案:

This is the angular way to do it...

<li ng-click="openNav(active = 1)" ng-class="{'active': active == 1 }">
<li ng-click="openNav(active = 2)" ng-class="{'active': active == 2 }">
<li ng-click="openNav(active = 3)" ng-class="{'active': active == 3 }">

Edit: Be aware, that you should replace active with something like active.nav so you wont run into issues later.

网友答案:

The active propery should refer to every item - think of it like enum - not like boolean working example: http://jsfiddle.net/prash/Cp73s/267/

var myapp = angular.module('sampleapp', [ ]);

myapp.controller('samplecontoller', function ($scope) {

  
 $scope.showData = function( ){

 
     $scope.datalists = [
    { "name": "Read about angular"},
    {"name": "Read about knockout"},
    {"name": "Read about backbone"},
    {"name": "Read about jquery"},
    {"name": "Read about javascript"}
    
]
}
 $scope.select= function(item) {       $scope.selected = item;};
$scope.isActive = function(item) {       return $scope.selected === item;};
});


 
.paginationclass{
    
margin: 19px 28px;    
}
.paginationclass div{
    cursor:pointer;
    text-decoration:underline;
}
.active{
    color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div ng-app="sampleapp">
    <div ng-controller="samplecontoller" ng-init="showData()">
        
        
 <ul>
 <li class="paginationclass" ng-repeat="datalist in datalists" ng-click="select(datalist)" ng-class="{active: isActive(datalist)}">
 <div>{{ datalist.name }} </div> 
 </li>
</ul> 
        
    
    
    
    </div>
</div>
网友答案:

You can add multiple conditions in ng-class

<li ng-click="openNav($event)" ng-class="{'active': isActive, 'normal': isNotActive }">
分享给朋友:
您可能感兴趣的文章:
随机阅读: