10

Can anyone offer the correct approach to this JSFiddle:

<style>
 .red #btn{
     background-color:red;
  }

 .blue #btn{
    background-color:blue;
  }
 </style>

 <body ng-app="ap" ng-controller="con">
    <button id="btn" ng-click="changeClass()">Change Class</button>    
 </body>

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

  app.controller("con",function($scope){

  $scope.class = "red";

  $scope.changeClass = function(){
     if ($scope.class === "red #btn")
         $scope.class = "blue #btn";
      else
         $scope.class = "red #btn";
   };
 });

 </script>

JsFiddle Link

I am trying to change the class of an element via .class & #ID.

Thanks in advance

Thanks tymeJV, new JSFiddle:

Solution

1 Answer 1

28

The correct approach would be using ng-class based on a toggle variable, consider:

CSS:

.red {
    color: red;
}

JS:

$scope.toggle = false;

HTML:

<button id="btn" ng-click="toggle = !toggle" ng-class="{'red' : toggle}">Change Class</button>

ng-class works by assigning the referenced class (in the above, "red") based on if the variable ("toggle") is true or false.

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

9 Comments

tymeJV: Question. What if I have a <div id="SomeDiv"></div> and I want to change it's color with the button click?
Put the ng-class on that element
tymeJV: I know I am pushing my luck here, hehe, but how to toggle between red and blue?
Ahh not sure of the syntax off the top of my head, but you can do it with ng-cass - try searching for ng-class if else
@tymeJV Have someone told you before ? You're genius :) Worked like a charm !!
|

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.