1

How can I make a button that will work as toggle, my function is something like this ->

$scope.update=(id, command)=> {
            if (command === "remove") {
                //logic to remove
            } else if (command === "add") {
                //logic to add
            }
        }

here I need to pass id and command as a parameter in ng-click.

<button ng-click="update(data.id, 'add')" class="btn btn-primary">Add</button>
<button ng-click="update(data.id, 'remove')" class="btn btn-warning">Remove</button>

currently I have to use two buttons to do the simple task, how can I make it like using one button I could be able to do the same!!

1 Answer 1

1

The piece you're missing is storing the toggled state of the button.

$scope.toggleButton = { inAddState: true };
$scope.update = (id, button) => {
    if (button.inAddState) {
        // logic to add
    } else {
        // logic to remove
    }
    // make sure you switch the state of the button at some point
    button.inAddState = !button.inAddState;
}
<button ng-click="update(data.id, toggleButton)" 
        class="btn {{ toggleButton.inAddState ? 'btn-primary' : 'btn-warning' }}"
        ng-bind="toggleButton.inAddState ? 'Add' : 'Remove'">
</button>

In this case, there are only two places within the element where the state must be considered: the class and the text. In my opinion, once you reach three or more, it's just simpler to use two elements with ng-if instead of having a bunch of conditionals inside one element. For example, if you wanted the title attribute to also be conditional.

<button ng-click="update(data.id, toggleButton)" 
        ng-if="toggleButton.inAddState"
        class="btn btn-primary"
        title="Click to add">
    Add
</button>
<button ng-click="update(data.id, toggleButton)" 
        ng-if="!toggleButton.inAddState"
        class="btn btn-warning"
        title="Click to remove">
    Remove
</button>

instead of

<button ng-click="update(data.id, toggleButton)" 
        class="btn {{ toggleButton.inAddState ? 'btn-primary' : 'btn-warning' }}"
        ng-bind="toggleButton.inAddState ? 'Add' : 'Remove'"
        title="Click to {{ toggleButton.inAddState ? 'add' : 'remove' }}">
</button>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you sir it helped me a lot. I got this for life :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.