1

I am new to angular. I have two button as I will click on button1 so its color will be change from green to red and after that I will click on button2, so button1 color will be again green. How I can do it using ng-click ?

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

and this is my app.js

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

Which code should i write in app.js ?

Priyanka
  • 170
  • 1
  • 3
  • 12
Abhay Sharma
  • 221
  • 1
  • 7
  • 24
  • [duplicate](http://stackoverflow.com/questions/20460369/adding-and-removing-classes-in-angularjs-using-ng-click) – elreeda Jul 07 '16 at 09:51

3 Answers3

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>
Arun Ghosh
  • 7,634
  • 1
  • 26
  • 38
1

Here is an example using the angular controller and setting 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>

Controller code

  // 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';
  };

Here is a JSFiddle

shammelburg
  • 6,974
  • 7
  • 26
  • 34
0

Add css class dynamically using ng-class directive on click event.

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

dreamweiver
  • 6,002
  • 2
  • 24
  • 39