Serhiy
Serhiy

Reputation: 1981

How to change background color of an item based on the click in AngularJs

I have listed a number of <div>s using ng-repeat.

When I click on one <div> (div1) background color becomes blue, and if I click on other div (div2) - div1-background-color becomes white as it was at the beginning and div2-background-color becomes blue.
Here is my html:

<div  ng-repeat="folder in vm.folders track by $index" >
    <span>{{folder.name}}</span>
</div>

Upvotes: 1

Views: 3246

Answers (3)

Mohit Tanwani
Mohit Tanwani

Reputation: 6628

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

app.controller("con",function($scope){
   $scope.changeIndex = function(index){
    $scope.selected = index;
  }
});
.blue{
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="ap" ng-controller="con">
<div ng-repeat="n in [10, 20, 30, 40] track by $index">
  <div ng-class="{blue: selected==$index}" ng-click="changeIndex($index)">{{n}}</div>
  </div>
</body>

Upvotes: 3

Andre.Anzi
Andre.Anzi

Reputation: 151

You should assign each div a function on click that saves the last clicked div id's. Then you have to use the ng-class directive to set a blue-background class to the div if his id is the current one.

$scope.setCurrent = function(index){
   $scope.currentId = index;
}

<div ng-repeat="folder in vm.folders track by $index" ng-click="setCurrent($index)" ng-class="{selected : currentId == $index}" >
    <span>{{folder.name}}</span>
</div>

Upvotes: 1

Sa E Chowdary
Sa E Chowdary

Reputation: 2075

html

<div  ng-repeat="folder in vm.folders track by $index" ng-click="setSelected($index)" ng-class="{selected : $index === selectedfolder }">
    <span>{{folder.name}}</span>
</div>

js

  $scope.selectedfolder = null;
    $scope.setSelected = function(selectedfolder ) {
       $scope.selectedfolder = selectedfolder ;
    }

css

.selected {
  background-color: blue;
}

Upvotes: 1

Related Questions