Alex
Alex

Reputation: 929

Adding an active class on ng-click function

I have 2 buttons and I just want to add a class when the button has been clicked.

       <button class="panel-btn" 
        ui-sref="basechat" 
        ng-click="setBaseChat()" id="base-chat-btn">Base Chat</button>
        <button class="panel-btn" 
        ui-sref="banner" 
        ng-click="setBannerChat()" 
        id="banner-chat-btn">Banner</button>

The function on ng-click returns a true value.

Hope you guys can help me, I still don't understand very well how ng-class works

Upvotes: 0

Views: 3895

Answers (3)

camden_kid
camden_kid

Reputation: 12813

As a simple example, you could have:

$scope.bannerClass = "baseClass"; // baseClass defined in your CSS

$scope.setBannerChat = function() {
    $scope.bannerClass = "myClass"; // myClass defined in your CSS
    // or $scope.bannerClass = "baseClass myClass";
}

and then:

<div ng-class="bannerClass">Hello</div>
<button ng-click=setBannerChat()></button>

Upvotes: 2

Quentin Donnellan
Quentin Donnellan

Reputation: 2832

If you want to add a class to a button on click you can do something like this:

<button ng-class="{someClass: someTruthyValue}" ng-click="someFunction()">

The ng-class will look at the value of someTruthyValue and display someClass if it is True, and not otherwise.

For example, your JS could look something like:

$scope.someTruthyValue = False;

$scope.someFunction = function() {
    $scope.someTruthyValue = True;
}

The docs are fairly good here

Also, as you can see in the other answers, there is more than 1 way to use ng-class, however I like my solution because it allows you the option to link additional button to reverse the class change:

<button ng-click="someReverseFunction()">

Where, certainly:

$scope.someReverseFunction = function() {
    $scope.someTruthyValue = False;
}

Upvotes: 2

JoMendez
JoMendez

Reputation: 884

You can do this in your controller:

 $scope.clickFucntion = function(){
     $scope.myClass = 'my-class';
 }

and this in your view:

 <button class="{{myClass}}" ng-click="clickFucntion()">

Upvotes: 0

Related Questions