使用ng-click单击其他按钮时按钮颜色更改

时间:2016-07-07 09:42:44

标签: javascript html angularjs

我是棱角分明的新人。我有两个按钮,因为我将点击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中编写哪些代码?

3 个答案:

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

答案 1 :(得分: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

答案 2 :(得分: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>

after selecting location from google places api