Onclick按钮更改AngularUI

时间:2014-02-06 00:34:54

标签: angularjs angular-ui

我正在尝试制作6个可选择的按钮。我在添加两个以上时遇到了麻烦。第三个按钮是选择其他按钮,单击两次按钮也会取消选择。这是不受欢迎的。一团糟。任何人都可以帮我解决这个问题吗? 这是我的代码:

    <div ng-app="plunker">
        <div ng-controller="MainCtrl">
            <button type="button" class="btn" ng-class="{'btn-primary':isUploadActive}" ng-click="toggleActive1()">Upload</button>

            <button type="button" class="btn" ng-class="{'btn-primary':isDownloadActive}" ng-click="toggleActive2()">Download</button>        
        </div>    
    </div>

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
    $scope.button1Active = false;
    $scope.button2Active = false;
        $scope.button3Active = false;
            $scope.button4Active = false;
                $scope.button5Active = false;
                    $scope.button6Active = false;

    $scope.toggleActive1 = function() {
        if($scope.button2Active) {
            $scope.button2Active = !$scope.button2Active;
        }
        $scope.button1Active = !$scope.button1Active;
    };

    $scope.toggleActive2 = function() {    
        if($scope.button1Active) {
            $scope.button1Active = !$scope.button1Active;
        }
        $scope.button2Active = !$scope.button2Active;
    };
  $scope.toggleActive3 = function() {    
        if($scope.button3Active) {
            $scope.button3Active = $scope.button3Active;
        }
        $scope.button2Active = !$scope.button2Active;
         $scope.button1Active = !$scope.button1Active;
          $scope.button4Active = !$scope.button4Active;
           $scope.button5Active = !$scope.button5Active;
            $scope.button6Active = !$scope.button6Active;
    };
});



<div id="contentDiv">

   <div ng-app="plunker">
    <div ng-controller="MainCtrl">
        <button type="button" class="btn" ng-class="{'btn-primary':button1Active}" ng-click="toggleActive1()">Upload</button>

        <button type="button" class="btn" ng-class="{'btn-primary':button2Active}" ng-click="toggleActive2()">Download</button>        
         <button type="button" class="btn" ng-class="{'btn-primary':button3Active}" ng-click="toggleActive3()">Purchased</button>   
    </div>    
</div>

1 个答案:

答案 0 :(得分:0)

糟糕!这有点乱。我做了一个似乎做你想做的小提琴:http://jsfiddle.net/qwah3/

基本上我只给控制器一个包含活动按钮的作用域对象,每个按钮只检查该值:

function myCtrl($scope) {
  $scope.active = { val : '' };
  $scope.Activate = function(buttonVal) {
    $scope.active.val = buttonVal;
  };
}

这意味着每个按钮都可以是这样的:

<button type="button" class="btn" ng-class="{'btn-primary':active.val == 'Download'}"
        ng-click="Activate('Download')">Download</button>

您甚至可以将按钮变为指令,使其更加轻松。

希望这有帮助!