0

I have two states for a button, "State1" and "State2".

It defaults to "State2". When I click the button, it toggles to "State1".
When I click anywhere outside the button, I need it to change from "State1" back to "State2". This is my code:

<div ng-click="Ctrl.Check = !Ctrl.Check">
            <a ng-class="{'btn-danger': !Ctrl.Check, 'btn-default': Ctrl.Check }" >
                {{ Ctrl.Check ? 'State1' : 'State2' }}
            </a>
</div>
5
  • Try adding class="btn" to the A element Commented Jan 31, 2017 at 22:27
  • When you say "click out of button" do you mean when the button loses focus (on-blur)? Commented Jan 31, 2017 at 22:31
  • @ryanyuyu I mean not click button to trigger toggle Commented Jan 31, 2017 at 22:32
  • Clicking anywhere outside of the button? Commented Jan 31, 2017 at 22:32
  • Yes, I mean this @ryanyuyu Commented Jan 31, 2017 at 22:32

1 Answer 1

1

It sounds like you're just checking whether the element has focus. This is much easier than putting down a bunch of ng-click handlers all over your form just to toggle one input.

Use ng-focus and the corresponding ng-blur. If you use HTML elements that can have focus (like a <button>), you can use code like

<button type="button" class="btn" 
    ng-class="{'btn-danger': !Ctrl.Check, 'btn-default': Ctrl.Check }" 
    ng-focus="Ctrl.Check = true"
    ng-blur="Ctrl.Check = false">
    {{ Ctrl.Check ? 'State1' : 'State2' }}
</button>

Demo on plnkr

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

2 Comments

How can you make it toggle when you click the button at the same time?
Wait. Toggle on click and on blur? That makes little sense. But you could just add ng-click="Ctrl.Check = !Ctrl.Check" or something like that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.