首页 > 技术文章 > 如何在angularjs里面选择一个按钮而不改变其他按钮的颜色

maomingchao 2017-04-04 22:27 原文

var selectJson = {
    "background-color": "#FF0000", /* Green */
    "border": "none",
    "color": "white",
    "padding": "15px 32px",
    "text-align": "center",
    "text-decoration": "none",
    "display": "inline-block",
    "font-size": "16px",
    "margin": "4px 2px",
    "cursor": "pointer"
};

var unselectJson = {
    "background-color": "#E5E5E5", /* Green */
    "border": "none",
    "color": "black",
    "padding": "15px 32px",
    "text-align": "center",
    "text-decoration": "none",
    "display": "inline-block",
    "font-size": "16px",
    "margin": "4px 2px",
    "cursor": "pointer"
};

var myApp1 = angular.module('myApp1', []);
myApp1.controller('myCtrl', function ($scope) {
    $scope.select = false;
    $scope.nameStyle = unselectJson;
    

    $scope.click = function (x) {  
        $scope.select = !$scope.select;
        if ($scope.select) {
            betPush(x);
            $scope.nameStyle = selectJson;
        }
        else {
            $scope.nameStyle = unselectJson;
        }
    };
});


var myValueApp = angular.module('myValueApp', []);
myValueApp.controller('valueCtrl', function ($scope) {
    $scope.valueGroup=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
    $scope.select = false;
    $scope.contents = [
        unselectJson, unselectJson, unselectJson, unselectJson, unselectJson, unselectJson, unselectJson, unselectJson,
        unselectJson, unselectJson, unselectJson, unselectJson, unselectJson, unselectJson, unselectJson, unselectJson
    ]
    $scope.clickValue = function (x) {
        $scope.select = !$scope.select;
        let index = x - 1;
        
        console.log(x);

        if ($scope.select) {
            $scope.contents[index] = selectJson;
            betPush(x);
        }
        else {
            $scope.contents[index] = unselectJson;
        }
    };
});

angular.module('myApp', ['myApp1', 'myValueApp']);

var m_arrBet = new Array();
function betPush(name) {
    m_arrBet.push(name);
    console.log(m_arrBet);
}


html 

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />   
    <script src="angular.min.js"></script>
    <script src="value.js"></script>
    
</head>
<body ng-app="myApp">
   
    <div  ng-init="names=['举例']" ng-controller="myCtrl" >
        <button ng-style="nameStyle"  ng-click="click(x)" ng-repeat="x in names">{{x}}</button>
    </div>

    <br />
    <br />
    <br />
    <div ng-controller="valueCtrl" >
        <button ng-model="x" ng-style="contents[$index]" id="btn{{$index}}"  ng-click="clickValue(x)" ng-repeat="x in valueGroup">{{x}}</button>
    </div>   
    
</body>

</html>



推荐阅读