puscan
puscan

Reputation: 35

Change button color after click in Angularjs

This is what I have now: index.html

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="TodoCtrl">
    <button class="btn btn-danger" ng-click="start()">Start</button>
  </div>
</div>


function TodoCtrl($scope) {
  $scope.start = function() {

  };
}

What can I fill in the $scope.start function so that once the button is clicked, the color of the button turns yellow.

Upvotes: 3

Views: 25431

Answers (2)

Ronnie
Ronnie

Reputation: 11198

you can use ng-class Define a var like $scope.started = false; and inside you start function set it to true. On your button do this:

ng-class="{'btn-warning': started, 'btn-danger': !started}"

another way to write it:

ng-class="started && 'btn-warning' || !started && 'btn-danger'"

note: remove btn-danger from your curre class attribute

EDIT

The newer, more common way is the standard ternary operator (also easier to read):

ng-class="started ? 'btn-warning' : 'btn-danger'"

Upvotes: 12

El Dude
El Dude

Reputation: 5618

The probably best way is to bind the button style to the variable like this:

<button class="button button-block {{buttonStyle}}" ng-click="start()">
    {{buttonText}}
</button>

and define buttonStyle and buttonText in your scope

$scope.buttonText = "Start";
$scope.buttonStyle="button-calm";

$scope.start = function(){
    $scope.buttonText = "Clicked!";
    $scope.buttonStyle="button-assertive";
}

Upvotes: 2

Related Questions