1

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>
4
  • What the blue background is supposed to mean? Is it kind of item selection or what? Commented Sep 6, 2016 at 10:41
  • What you have tried? Commented Sep 6, 2016 at 10:43
  • yes it's kind of item selection Commented Sep 6, 2016 at 10:56
  • @Serhiy try my answer stackoverflow.com/a/39347164/6608101 Commented Sep 6, 2016 at 10:59

3 Answers 3

3

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.