Instead of utilizing $rootScope
, you can set up a listener to observe view changes using $routeChangeSuccess
(assuming you employed $routeProvider
for view transitions). Ensure you have a parent controller where you establish this listener.
For example:
var app = angular.module('myApp', ['ngRoute']);
app.controller('parentController', function($scope, $route) {
$scope.$on('$routeChangeSuccess', function(newValue, oldValue) {
if ( newValue !== oldValue ) {
$scope.bodyClass = $route.current.viewClass;
}
});
});
Your route configuration should look like this:
app.config(function($routeProvider) {
$routeProvider.when('/list',{
controller: 'listController',
templateUrl: '/list.html',
viewClass: 'class1'
}).when('/details', {
controller: 'detailsController',
templateUrl: '/details.html',
viewClass: 'class2'
}).otherwise({
redirectTo: '/list'
});
});
Therefore, your HTML structure should resemble:
<body ng-controller="parentController" class="commonClasses" ng-class="bodyClass ">
Check out the PLUNKER DEMO for more information.