Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs toggle ng-class ng-click

Tags:

angularjs

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

like image 431
Mike Jones Avatar asked Feb 27 '14 14:02

Mike Jones


People also ask

How do I toggle a class in Angularjs?

The toggling of the class can be done in 2 ways, i.e., either specifying the value to 0 or 1, depending upon the condition satisfied, by initially defining the value as 0, or depending on the boolean value, i.e., true or false, with satisfying the required condition, by initially setting the value as true.

What is the difference between Ng-click and Onclick?

Another significant difference between ng-click and onclick is the execution context. Code inside an onclick attribute executes against the global window object, while an expression inside of ng-click executes against a specific scope object, typically the scope object representing the model for the current controller.

What is Ng-click?

ng-click is an attribute of an HTML element that can be used for the customized components in Angular. We use this attribute to detect if an element is clicked and tracks the mouse's cursor. ng-click takes a function as an attribute and calls it whenever an element is clicked.


1 Answers

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.

like image 116
tymeJV Avatar answered Sep 21 '22 23:09

tymeJV