AngularJS - Using $rootScope.

by Yure Pereira

HTML

<div ng-app="app" class="{{backgroundColor}}" id="app">
  
  <div class="ctrl {{ctrlColor}}" ng-controller="HomeCtrl" ng-click="changeBackgroundColor('red')">
    
  </div>
  
  <div class="ctrl {{ctrlColor}}" ng-controller="ContatoCtrl" ng-click="changeBackgroundColor(ctrlColor)">
    
  </div>
  
  <div class="ctrl {{ctrlColor}}" ng-controller="SobreCtrl" ng-click="changeBackgroundColor(ctrlColor)">
    
  </div>
  
</div>

CSS

#app {
  width: 200px;
  padding: 20px;
}

#app .ctrl {
  height: 50px;
  margin: 10px;
}

.init {
  background-color: #ddd;
}
.red {
  background-color: #f00;
}
.blue {
  background-color: #00f;
}
.green {
  background-color: #0f0;
}

JavaScript

var app = angular.module('app', []);

app.run(['$rootScope', function($rootScope) {

  $rootScope.backgroundColor = 'init';
  
  $rootScope.changeBackgroundColor = function(color) {
		$rootScope.backgroundColor = color;
  };
  
}]);

app.controller('HomeCtrl', ['$scope', '$rootScope', function($scope, $rootScope) {

	$scope.ctrlColor = 'red';

}]);

app.controller('ContatoCtrl', ['$scope', '$rootScope', function($scope, $rootScope) {

	$scope.ctrlColor = 'blue';

}]);

app.controller('SobreCtrl', ['$scope', '$rootScope', function($scope, $rootScope) {

	$scope.ctrlColor = 'green';

}]);