2016-07-07 209 views
0

我是新来的角度。我有两个按钮,因为我会点击button1,所以它的颜色会从绿色变成红色,之后我会点击button2,所以button1颜色会再次变成绿色。如何使用ng-click来做到这一点?使用ng-click单击其他按钮时的按钮颜色变化

它我的index.html

<!DOCTYPE html> 
 
<html ng-app="myApp"> 
 
<head> 
 
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> 
 
\t <script type="text/javascript" src="app.js"></script> 
 

 
\t <title></title> 
 
</head> 
 
<body ng-controller ="testCtrl" > 
 
<button type="button" class="btn btn-default" ng-click="chngcolor()" >Chnage Color</button> 
 
<button type="button" class="btn btn-default" ng-click="chcolor()" >Pre Color</button> 
 
</body> 
 
</html>

,这是我的app.js

var myApp = angular.module("myApp",[]); 
 
\t myApp.controller('testCtrl', function($scope){ 
 
\t \t $scope.chngcolor = functionn{ 
 
\t \t 
 
\t \t }; 
 
\t }); 
 

我应该在应用程序写哪个代码。 Ĵ是吗?

+0

[重复](http://stackoverflow.com/questions/20460369/adding-and-删除类中的角度使用ng单击) – Gintoki

回答

0

这里是使用角控制器和设定一个例子ng-style

<div ng-controller="MainController"> 
    <button type="button" class="btn btn-default" ng-click="chngcolor()" ng-style="color">Change Color</button> 
    <button type="button" class="btn btn-default" ng-click="chcolor()">Pre Color</button> 
</div> 

控制器代码

// set default color 
    $scope.color = {'background-color': 'green'}; 

    $scope.chngcolor = function() { 
    $scope.color = {'background-color': 'red'}; 
    }; 

    $scope.chcolor = function() { 
    $scope.color = {'background-color': 'green'}; 
    // Shorter way to for the same result 
    // $scope.color.backgroundColor = 'green'; 
    }; 

这里是一个JSFiddle

+0

现在感谢它的工作。 –

1
<button type="button" class="btn btn-default" ng-class="color" ng-click="color=red" ng-init="color=green">Chnage Color</button> 
<button type="button" class="btn btn-default" ng-click="color=green" >Pre Color</button> 

<style> 
    .green { 
     color: green; 
    } 
    .red { 
     color: red; 
    } 
</style> 
0

添加css类上动态使用ng-class指令点击事件。

CSS:

.red-color { 
    background-color: red; 
} 

.green-color { 
    background-color: green; 
} 

HTML:

<button type="button" class="btn btn-default" ng-class="color" ng-click="color='red-color'">Change Color</button> 
    <button type="button" class="btn btn-default" ng-click="color='green-color'">Pre Color</button> 

Live Demo @ JSFiddle