繁体   English   中英

使用ng-click单击其他按钮时按钮颜色发生变化

[英]Button color change on click at other button using ng-click

我是新手。 我有两个按钮,因为我将单击button1,因此其颜色将从绿色更改为红色,然后单击button2,因此button1的颜色将再次变为绿色。 我如何使用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> <script type="text/javascript" src="app.js"></script> <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",[]); myApp.controller('testCtrl', function($scope){ $scope.chngcolor = functionn{ }; }); 

我应该在app.js中编写哪些代码?

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

这是使用角度控制器并设置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

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

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>

现场演示@ JSFiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM