adding and removing classes in angularJs using ng-click
angularjs, angularjs-ng-click, javascript, ng-class
Solution
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
Problem
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; }); ```