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 ?

1
  • duplicate Commented Jul 7, 2016 at 9:51

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.