How to swap between 3 or more classes in Angular targeting only the element that is clicked?
I would like the element to switch between 3 CSS classes when clicked. I have seen other solutions that work when only 2 classes are switched like this one . They are based on true and false conditions, so they won't work for more than 2 grades.
I got it to be swapped between 3 classes, however, clicks on targets all items instead of clicking one item. Here's my code so far : `
$scope.iconClass = "green";
$scope.iconClicked = function () {
switch ($scope.iconClass) {
case "green":
$scope.iconClass = "red";
break;
case "red":
$scope.iconClass = "blue";
break;
default:
$scope.iconClass = "green";
}
};`
And the html is here: `
<li class="item" ng-class="iconClass" ng-click="iconClicked()"> Item 1 <br> </li>
<li class="item" ng-class="iconClass" ng-click="iconClicked()"> Item 2 <br> </li>
<li class="item" ng-class="iconClass" ng-click="iconClicked()"> Item 3 <br> </li>
`
How can I do this without creating a different iconClass variable for every other element ? I'm sure there is a simple, elegant solution for this.
source to share
ng-class
supports adding multiple classes based on boolean expressions using scope variables.
class = "ng-class: expression;"
Expression for eval. The evaluation result can be a string representing whitespace-delimited class names, an array, or a map of class names for boolean values.
You can achieve this with ng-class="{'red':'iconclass == red', 'blue':'iconClass == blue'}"
You can use the SWAP button to change the colors that you are looking for.
An example example can be found here: http://plnkr.co/edit/lzHkZaBn1RQv24LaxQYT?p=preview
source to share
Don't know if this will fit your requirement, but you can create an array and loop through it using a directive ng-repeat
like this
<li class="item" ng-repeat="item in items track by $index" ng-class="item.class" ng-click="iconClicked(item)"> {{item.name}} <br> </li>
area items
array
$scope.items = [{"name":"Item 1","class":"black"},{"name":"Item 1","class":"black"},{"name":"Item 1","class":"black"}]
additional css class.
.black{
color: black;
}
change onclick function like this
$scope.iconClicked = function (item) {
$scope.items = $scope.items.map(function(o){
o.class = "black"
return o;
} )
item.class = "red";
};
Please note that the color will be highlighted in red and others will be black
source to share
I had to create a custom scoped directive for this to happen.
Does anyone know a better idea? It would be more than nice.
function ListItem() {
var ddo = {
template: '<li class="item" ng-class="iconClass" ng-click="iconClicked()"> Item 1 (isolate) <br> </li>',
scope: {
items: '<'
},
controller: 'MyController'
};
return ddo;
}
source to share