Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js How to change an elements css class on click and to remove all others

Tags:

angularjs

i'm trying to make my two elements toggle, so if one element is clicked it will remove all references of my-class and apply it to its self. Any ideas?

<span id="1" ng-style="my-class" ng-click="tog=my-class"></span>  <span id="2" ng-style="my-class" ng-click="tog=my-class"></span> 

Cheers!

like image 852
TheNickyYo Avatar asked Jul 29 '13 15:07

TheNickyYo


People also ask

How do I change a specific class in CSS?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)

How do you remove a class from an element in CSS?

The syntax for Removing CSS classes to an element:removeClass(class_name);


2 Answers

Create a scope property called selectedIndex, and an itemClicked function:

function MyController ($scope) {   $scope.collection = ["Item 1", "Item 2"];    $scope.selectedIndex = 0; // Whatever the default selected index is, use -1 for no selection    $scope.itemClicked = function ($index) {     $scope.selectedIndex = $index;   }; } 

Then my template would look something like this:

<div>       <span ng-repeat="item in collection"              ng-class="{ 'selected-class-name': $index == selectedIndex }"              ng-click="itemClicked($index)"> {{ item }} </span> </div> 

Just for reference $index is a magic variable available within ng-repeat directives.

You can use this same sample within a directive and template as well.

Here is a working plnkr:

http://plnkr.co/edit/jOO8YdPiSJEaOcayEP1X?p=preview

like image 117
Jesse Earle Avatar answered Sep 21 '22 18:09

Jesse Earle


have you tried with a condition in ng-class like here : http://jsfiddle.net/DotDotDot/zvLvg/ ?

    <span id='1' ng-class='{"myclass":tog==1}' ng-click='tog=1'>span 1</span>     <span id='2' ng-class='{"myclass":tog==2}' ng-click='tog=2'>span 2</span> 
like image 31
DotDotDot Avatar answered Sep 23 '22 18:09

DotDotDot