简体   繁体   中英

How to make a toggle button in Angularjs

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!!

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM