Home > Software design >  How to make a toggle button in Angularjs
How to make a toggle button in Angularjs

Time:12-23

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')" >Add</button>
<button ng-click="update(data.id, 'remove')" >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!!

CodePudding user response:

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)" 
        
        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"
        
        title="Click to add">
    Add
</button>
<button ng-click="update(data.id, toggleButton)" 
        ng-if="!toggleButton.inAddState"
        
        title="Click to remove">
    Remove
</button>

instead of

<button ng-click="update(data.id, toggleButton)" 
        
        ng-bind="toggleButton.inAddState ? 'Add' : 'Remove'"
        title="Click to {{ toggleButton.inAddState ? 'add' : 'remove' }}">
</button>
  • Related