Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 406
puscan Avatar asked Jul 17 '26 13:07

puscan


1 Answers

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'"

like image 159
Ronnie Avatar answered Jul 19 '26 04:07

Ronnie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!