AngularJS类在按钮上切换

时间:2016-06-02 20:58:59

标签: angularjs

我正在尝试在单击按钮时切换类。 IE:如果选择了按钮'rndTotal',则添加“selected”类,并删除其他按钮“selected”类。我也需要这种方法来使用我的控制器,因为我会根据选择的内容发生事情。

到目前为止,我有:

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

默认为'exact',但除此之外不起作用。

1 个答案:

答案 0 :(得分:1)

这感觉就像一个黑客,但要完成你所能做到的事情之后:

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

<强>更新

我不会像这样直接在标记中设置模型值,而是转向使用控制器。为此,我会做出以下更改:

控制器

.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
    };
});

标记

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