[javascript] adding and removing classes in angularJs using ng-click

I am trying to work how to add a class with ngClick. I have uploaded up my code onto plunker Click here. Looking at the angular documentation i can't figure out the exact way it should be done. Below is a snippet of my code. Can someone guide me in the right direction

 <div ng-show="isVisible" ng-class="{'selected': $index==selectedIndex}" class="block"></div>

Controller

var app = angular.module("MyApp", []);
app.controller("subNavController", function ($scope){

        $scope.toggle = function (){
            $scope.isVisible = ! $scope.isVisible;
        };

        $scope.isVisible = false;
    });

This question is related to javascript angularjs angularjs-ng-click ng-class

The answer is


_x000D_
_x000D_
var app = angular.module("MyApp", []);_x000D_
app.controller("subNavController", function ($scope){_x000D_
_x000D_
        $scope.toggle = function (){_x000D_
            $scope.isVisible = ! $scope.isVisible;_x000D_
        };_x000D_
_x000D_
        $scope.isVisible = false;_x000D_
    });
_x000D_
<div ng-show="isVisible" ng-class="{'active':isVisible}" class="block"></div>
_x000D_
_x000D_
_x000D_


you can also do that in a directive, if you want to remove the previous class and add a new class

    .directive('toggleClass', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                if(element.attr("class") == "glyphicon glyphicon-pencil") {
                    element.removeClass("glyphicon glyphicon-pencil");
                    element.addClass(attrs.toggleClass);
                } else {
                    element.removeClass("glyphicon glyphicon-ok");
                    element.addClass("glyphicon glyphicon-pencil");
                }
            });
        }
    };
});

and in your template:

<i class="glyphicon glyphicon-pencil" toggle-class="glyphicon glyphicon-ok"></i>

If you prefer separation of concerns such that logic for adding and removing classes happens on the controller, you can do this

controller

 (function() {
    angular.module('MyApp', []).controller('MyController', MyController);

    function MyController() {
      var vm = this;
      vm.tab = 0;

      vm.setTab = function(val) {
          vm.tab = val;
       };
      vm.toggleClass = function(val) {
          return val === vm.tab;
           };
        }
    })();

HTML

<div ng-app="MyApp">
  <ul class="" ng-controller="MyController as myCtrl">
    <li ng-click="myCtrl.setTab(0)" ng-class="{'highlighted':myCtrl.toggleClass(0)}">One</li>
    <li ng-click="myCtrl.setTab(1)" ng-class="{'highlighted':myCtrl.toggleClass(1)}">Two</li>
    <li ng-click="myCtrl.setTab(2)" ng-class="{'highlighted':myCtrl.toggleClass(2)}">Three</li>
   <li ng-click="myCtrl.setTab(3)" ng-class="{'highlighted':myCtrl.toggleClass(3)}">Four</li>
 </ul>

CSS

.highlighted {
   background-color: green;
   color: white;
}

I can't believe how complex everyone is making this. This is actually very simple. Just paste this into your html (no directive./controller changes required - "bg-info" is a bootstrap class):

<div class="form-group col-md-12">
    <div ng-class="{'bg-info':     (!transport_type)}"    ng-click="transport_type=false">CARS</div>
    <div ng-class="{'bg-info': transport_type=='TRAINS'}" ng-click="transport_type='TRAINS'">TRAINS</div>
    <div ng-class="{'bg-info': transport_type=='PLANES'}" ng-click="transport_type='PLANES'">PLANES</div>
</div>

for Reactive forms -

HTML file

_x000D_
_x000D_
<div class="col-sm-2">_x000D_
  <button type="button"  [class]= "btn_class"  id="b1" (click)="changeMe()">{{ btn_label }}</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

TS file

_x000D_
_x000D_
changeMe() {_x000D_
  switch (this.btn_label) {_x000D_
    case 'Yes ': this.btn_label = 'Custom' ;_x000D_
    this.btn_class = 'btn btn-danger btn-lg btn-block';_x000D_
    break;_x000D_
    case 'Custom': this.btn_label = ' No ' ;_x000D_
    this.btn_class = 'btn btn-success btn-lg btn-block';_x000D_
    break;_x000D_
    case ' No ': this.btn_label = 'Yes ';_x000D_
      this.btn_class = 'btn btn-primary btn-lg btn-block';_x000D_
      break;_x000D_
  }
_x000D_
_x000D_
_x000D_


You have it exactly right, all you have to do is set selectedIndex in your ng-click.

ng-click="selectedIndex = 1"

Here is how I implemented a set of buttons that change the ng-view, and highlights the button of the currently selected view.

<div id="sidebar" ng-init="partial = 'main'">
    <div class="routeBtn" ng-class="{selected:partial=='main'}" ng-click="router('main')"><span>Main</span></div>
    <div class="routeBtn" ng-class="{selected:partial=='view1'}" ng-click="router('view1')"><span>Resume</span></div>
    <div class="routeBtn" ng-class="{selected:partial=='view2'}" ng-click="router('view2')"><span>Code</span></div>
    <div class="routeBtn" ng-class="{selected:partial=='view3'}" ng-click="router('view3')"><span>Game</span></div>
  </div>

and this in my controller.

$scope.router = function(endpoint) {
    $location.path("/" + ($scope.partial = endpoint));
};

I used Zack Argyle's suggestion above to get this, which I find very elegant:

CSS:

.active {
    background-position: 0 -46px !important;
}

HTML:

<button ng-click="satisfaction = 'VeryHappy'" ng-class="{active:satisfaction == 'VeryHappy'}">
    <img src="images/VeryHappy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Happy'" ng-class="{active:satisfaction == 'Happy'}">
    <img src="images/Happy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Indifferent'" ng-class="{active:satisfaction == 'Indifferent'}">
    <img src="images/Indifferent.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'Unhappy'" ng-class="{active:satisfaction == 'Unhappy'}">
    <img src="images/Unhappy.png" style="height:24px;" />
</button>
<button ng-click="satisfaction = 'VeryUnhappy'" ng-class="{active:satisfaction == 'VeryUnhappy'}">
    <img src="images/VeryUnhappy.png" style="height:24px;" />
</button>

I want to add or remove "active" class in my code dynamically on ng-click, here what I have done.

<ul ng-init="selectedTab = 'users'">
   <li ng-class="{'active':selectedTab === 'users'}" ng-click="selectedTab = 'users'"><a href="#users" >Users</a></li>
   <li ng-class="{'active':selectedTab === 'items'}" ng-click="selectedTab = 'items'"><a href="#items" >Items</a></li>
</ul>

There is a simple and clean way of doing this with only directives.

<div ng-class="{'class-name': clicked}" ng-click="clicked = !clicked"></div>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to angularjs-ng-click

AngularJS : ng-click not working How to trigger ngClick programmatically Automatically pass $event with ng-click? adding and removing classes in angularJs using ng-click AngularJS ng-click stopPropagation Pass a reference to DOM object with ng-click Adding parameter to ng-click function inside ng-repeat doesn't seem to work How/when to use ng-click to call a route?

Examples related to ng-class

Angular ng-class if else adding and removing classes in angularJs using ng-click Adding multiple class using ng-class AngularJS ng-class if-else expression