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

时间:2016-10-23 05:14:22

标签: javascript angularjs ng-class

我有一个按钮组,其中一个按钮的类为“active”,由ng-class(myCtrl.onactive或myCtrl.offactive)设置为true

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

我正在尝试点击任何一个按钮来拥有活动类(而另一个没有)

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

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

2 个答案:

答案 0 :(得分:0)

下面是工作代码片段,只需在JS中添加以下函数

即可

./../epics/loginEpic

export const loginEpic = action$ =>
    action$.ofType("LOGIN")
        .mergeMap(action =>

            Observable.fromPromise(axios.post('webapi/login', action.payload))
                .flatMap(payload =>
                    // Concat multiple observables so they fire sequentially
                    Observable.concat(
                        // after LOGIN_FULILLED
                        Observable.of({ type: "LOGIN_FULFILLED", payload: payload.data.aid }),                   
                        // ****This is where I think I should be registering the epics right after logging in. "ANOTHER_ACTION" below depends upon one of these epics****     
                        Observable.of({type: "ANOTHER_ACTION", payload: 'webapi/following'}),
                        Observable.of({type: "LOGIN_SEQUENCE_DONE"}),
                    )
                )
                .startWith({ type: "LOGIN_PENDING" })
                .takeUntil(action$.ofType("LOGIN_CANCELLED"))
                .catch(error => Observable.of({
                    type: "LOGIN_REJECTED",
                    payload: error,
                    error: true
                }))
        );
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;
}

答案 1 :(得分:-1)

我认为你可以通过仅控制HTML来获得这个问题的解决方案,而不需要在控制器中创建函数 看看我为你准备好的小提琴 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>