【问题标题】:How to make a toggle button in Angularjs如何在Angularjs中制作一个切换按钮
【发布时间】:2022-01-23 20:47:53
【问题描述】:

如何制作一个可以用作切换按钮的按钮,我的功能是这样的 ->

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

这里我需要将id和command作为参数传入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>

目前我必须使用两个按钮来完成简单的任务,我怎样才能让它像使用一个按钮一样我可以做同样的事情!

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您缺少的部分是存储按钮的切换状态。

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

    在这种情况下,元素中只有两个地方必须考虑状态:类和文本。在我看来,一旦达到三个或更多,将两个元素与ng-if 一起使用会更简单,而不是在一个元素中包含一堆条件。例如,如果您希望 title 属性也是有条件的。

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

    而不是

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

    【讨论】:

    • 谢谢先生,这对我帮助很大。我得到了这一辈子 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多