Abhay Sharma Abhay Sharma - 3 months ago 58x
AngularJS Question

Button color change on click at other button using ng-click

I am new on 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 to ican do it using ng-click ?

Its my index.html

<!DOCTYPE html>
<html ng-app="myApp">
<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>

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

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 ?


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>

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