nc45 nc45 - 6 months ago 9
AngularJS Question

AngularJS class toggle on buttons

I'm trying to toggle a class when a button is clicked. IE: if button 'rndTotal' is selected, class "selected" is added, and the other buttons have class "selected" removed. I also need this approach to work with my controller, as in, I will have stuff happen based on what is selected.

So far I have:

<div class="row optionRow" ng-init="option = 'exact'" >
<div class="col">
<button ng-class="{selected:option=='exact'}">Exact</button>
</div>
<div class="col">
<button ng-class="{selected:option=='rndTip'}">Round Tip</button>
</div>
<div class="col">
<button ng-class="{selected:option=='rndTotal'}">Round Total</button>
</div>
</div>


It defaults to 'exact' but doesn't function other than that.

Lex Lex
Answer

This feels like a hack, but to accomplish what you're after you could do this:

<div class="row optionRow" ng-init="option = 'exact'" >
    <div class="col">
        <button ng-class="{selected:option=='exact'}" ng-click="option='exact'">Exact</button>
    </div>
    <div class="col">
        <button ng-class="{selected:option=='rndTip'}" ng-click="option='rndTip'">Round Tip</button>
    </div>
    <div class="col">
        <button ng-class="{selected:option=='rndTotal'}" ng-click="option='rndTotal'">Round Total</button>
    </div>
</div>

Update

Instead of setting model values directly in the markup like this, I would move to using a controller. In order to do that I would make the following changes:

Controller

.controller('myController', function() {
    var vm = this;
    vm.selectedOption = 'exact';
    vm.selectOption = function(option) {
        vm.selectedOption = option;
        // do anything else you may need to do when the selected option changes
    };
});

Markup:

<div ng-controller="myController as vm">
    <div class="row optionRow">
        <div class="col">
            <button ng-class="{selected:vm.selectedOption==='exact'}" ng-click="vm.selectOption('exact')">Exact</button>
        </div>
        <div class="col">
            <button ng-class="{selected:vm.selectedOption==='rndTip'}" ng-click="vm.selectOption('rndTip')">Round Tip</button>
        </div>
        <div class="col">
            <button ng-class="{selected:vm.selectedOption==='rndTotal'}" ng-click="vm.selectOption('rndTotal')">Round Total</button>
        </div>
    </div>
</div>
Comments