Angular JS:使用 ng-class 切换 2 个按钮

Angular JS: Toggle 2 buttons with an ng-class

我有一个按钮组,其中一个按钮的 class "active" 由它的 ng-class(myCtrl.onactive 或 myCtrl.offactive)设置为真

<div class="btn-group pull-right">
        <button ng-class="{active: myCtrl.onactive}" class="btn" ng-click="myCtrl.changeColorIcons()">on</button>
        <button ng-class="{active: myCtrl.offactive}" class="btn" ng-click="myCtrl.changeColorIcons()">off</button>
</div>

我正在尝试使单击哪个按钮都处于活动状态 class(而另一个则没有)

到目前为止,我正在我的控制器中尝试这个(不工作,但这是我想要的),一定有更好的方法...

self.onactive = true; //by default the "on" button is active

//but when a button is clicked turn the one that's active off and make the other active
this.changeColorIcons = function() {
    (self.onactive) ? self.offactive = true; self.onactive = false; : self.onactive = true; self.offactive = false;
};

我想你可以通过改变 HTML 来解决这个问题,不需要在控制器中创建函数 看看我为你准备的fiddle http://jsfiddle.net/Lvc0u55v/11094/

或者将您的 HTML 代码替换为以下代码:

<div class="btn-group pull-right">
<button ng-class="onactive" class="btn" ng-click="onactive='active'; offactive='inactive';">on</button>
<button ng-class="offactive" class="btn" ng-click="offactive='active';onactive='inactive'">off</button>
</div>

下面是有效的代码片段,只需在您的 JS 中添加以下函数即可

var app = angular.module("app", []);
app.controller("Ctrl", ["$scope",
  function($scope) {

    var myCtrl = this;
    myCtrl.onactive = true;
    myCtrl.offactive = false;

  myCtrl.changeColorIcons = function(button) {

      if (button === 'on') {
        myCtrl.onactive = true;
        myCtrl.offactive = false;
      } else if ( button === 'off') {
        myCtrl.onactive = false;
        myCtrl.offactive = true;
      }
    };
  }
]);
.active {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="Ctrl as myCtrl" class="btn-group pull-right">
    <button ng-class="{active: myCtrl.onactive}" class="btn" ng-click="myCtrl.changeColorIcons('on')">on</button>
    <button ng-class="{active: myCtrl.offactive}" class="btn" ng-click="myCtrl.changeColorIcons('off')">off</button>
  </div>
</div>