3

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.

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

6 Comments

I'm really new to Angularjs. The button still doesn't turn yellow after I follow this steps. Any more changes I should make?
are you using bootstrap? btn-danger is a red button and btn-warning is yellow...granted you're using bootstrap
Great it's working now! Another question is that if I add ng-disabled attributes in my button, how to make the button grey after ng-desabled is equal to true? Thanks a lot
want to have 2 different colors(grey and blue) for 2 states of the button ACTIVE and INACTIVE. Please help THANX
@SagarDevanga so make a class with the colors you want and use the same logic
|
2

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";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.