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; });
You could have ng-click that can toggle selected flag, that could be use with ng-class to bind / unbind class. You could easily do this by using ng-repeat which will reduce your line of code.
The ng-click directive tells AngularJS what to do when an HTML element is clicked.
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>
You just need to bind a variable into the directive "ng-class" and change it from the controller. Here is an example of how to do this:
var app = angular.module("ap",[]); app.controller("con",function($scope){ $scope.class = "red"; $scope.changeClass = function(){ if ($scope.class === "red") $scope.class = "blue"; else $scope.class = "red"; }; });
.red{ color:red; } .blue{ color:blue; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="ap" ng-controller="con"> <div ng-class="class">{{class}}</div> <button ng-click="changeClass()">Change Class</button> </body>
Here is the example working on jsFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With