更改按钮颜色onclick AngularUI

时间:2014-02-04 05:27:09

标签: angularjs button angular-ui

我有两个按钮。当我点击它们时它们都变成蓝色。任何人都可以向我解释如何制作它,以便在唯一选择的是蓝色和未选择时返回白色? 这是我的网站:http://test.shibagames.com

另外,为什么点击它时下拉列表不起作用?

3 个答案:

答案 0 :(得分:3)

两个按钮变为蓝色的原因是因为两个按钮都与相同的状态变量$scope.isActive相关联。您需要保留两个不同的状态变量来管理这两个按钮。

此外,下拉列表未显示的原因是bootstraps javascript无法以其默认形式使用angular。你需要使用angular-ui-bootstrap,http://angular-ui.github.io/bootstrap/

之类的东西

编辑(更新):

您可以按如下方式执行按钮:

ng-class="{'btn-primary': active == 'upload'}" ng-click="activateButton('upload')"

请注意,您通常无需关闭btn-default,因为btn-primary无论如何应该覆盖样式(但这取决于您)。

然后有范围功能:

$scope.activateButton = function(name) { $scope.active = name; }

至于ui-bootstrap不工作,你真的需要按照网站首页上的简单说明进行操作。在安装下,它解释了您需要添加ui.bootstrap模块依赖项:

angular.module('myModule', ['ui.bootstrap']);

答案 1 :(得分:1)

问题是当范围变量isActive为真时,将btn类更改为btn-primary。因此,通过点击其中任何一个toggleActive()被触发,将isActive设置为true并将两者都设置为“蓝色”。

简单的解决方案就像:

<button type="button" class="btn btn-default" ng-class="{'btn-primary':isActiveUpload,  'btn-default':!isActiveUpload}" ng-click="isActiveUpload = !isActiveUpload">Upload</button>

<button type="button" class="btn btn-default" ng-class="{'btn-primary':isActiveDownload,   'btn-default':!isActiveDownload}" ng-click="isActiveDownload = !isActiveDownload">Download</button>

答案 2 :(得分:1)

你也可以这样做。

<div ng-app="plunker">
    <div  ng-controller="MainCtrl" ng-init="buttons = [ {name : 'Upload', isActive :true},{name : 'Download', isActive : false}]">
        <button type="button" ng-repeat="btn in buttons" class="btn" ng-class="{'btn-primary':btn.isActive,  'btn-default':!btn.isActive}" ng-click="toggleActive(btn)">{{btn.name}}</button>
    </div>    
</div>


var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
    $scope.toggleActive = function(btn) {    
        btn.isActive = !btn.isActive;
    };
});

更新了要切换的来源

<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.isUploadActive = false;
    $scope.isDownloadActive = false;

    $scope.toggleActive1 = function() {
        if($scope.isDownloadActive) {
            $scope.isDownloadActive = !$scope.isDownloadActive;
        }
        $scope.isUploadActive = !$scope.isUploadActive;
    };

    $scope.toggleActive2 = function() {    
        if($scope.isUploadActive) {
            $scope.isUploadActive = !$scope.isUploadActive;
        }
        $scope.isDownloadActive = !$scope.isDownloadActive;
    };

});