简体   繁体   中英

AngularJS Changing <body> class using global variable

I just created a angularJS application.

Here is my index.html

<html ng-app="MyApp">
  <head>
    <!-- CSS files import -->
  </head>
  <body class="{{bodylayout}}">
    <div ng-view></div>
  </body>
  <--! JS imports 
   aungular.js
   app.js
   login.js
   register.js
   -->
</html>

app.js

'use strict';
//Define Routing for app
angular.module('myApp', []).config(['$routeProvider', '$locationProvider',
  function($routeProvider,$locationProvider) {
    $routeProvider
    .when('/login', {
        templateUrl: 'login.html',
        controller: 'LoginController'
    })
    .when('/register', {
        templateUrl: 'register.html',
        controller: 'RegisterController'
      })
    .when('/forgotPassword', {
        templateUrl: 'forgotpassword.html',
        controller: 'forgotController'
      })
   .when('/home', {
       templateUrl: 'views/home.html',
    })
    .otherwise({
       redirectTo: '/login'
    });
//    $locationProvider.html5Mode(true); //Remove the '#' from URL.
}]);

I have login.html, register.html, and forgotpassword.html, home.html. Each one has separate Controlers in separate files. login.js, register.js, forgot.js, home.js.

login.js

'use strict';

angular.module('myApp').controller('LoginController', function($scope, $location, $window) {
    $scope.user = {};
    $scope.loginUser=function()
    {
        var username=$scope.user.name;
        var password=$scope.user.password;
        if(username=="admin" && password=="admin123")
        {
            $location.path( "/home" );  
        }
        else
        {
            $scope.message="Error";
            $scope.messagecolor="alert alert-danger";
        }
    }
});

Similarly, I have post methods in other controllers.

What I want is, when the view is login or register or forgotpassword, the body class should be "login-layout" . So in body I put class="{{bodylayout}} ". I know using global variables, the value can be set. But I don't know how to.

In app.js I tried this

angular.module('myApp').factory("myService", function(){

      return {
        sharedObject: { data: 'login-layout' }
      }; 

    });

But don't know how to use it.

You can create global variables in two way

Using $rootScope you can do something like in your LoginController controller

angular.module('myApp').controller('LoginController', function($scope, $location, $window, $rootScope) {
   $scope.user = {};
   $rootScope.bodylayout = 'login-layout';

   //others code 
}

Using service

angular.module('myApp').factory("myService", function(){

      return {
        sharedObject: { data: 'login-layout' }
      }; 

});

Use this service in your controller

angular.module('myApp').controller('LoginController', function($scope, $location, $window, myService) {
       $scope.user = {};
       $rootScope.bodylayout = myService.sharedObject.data; // get data from service

       //others code 
    }

Where your HTML looks like

<body class="{{bodylayout}}">

Note in this case you need to set bodylayout in each controller otherwise it use the old value

Try using the $rootScope:

$rootScope.bodyClass = 'login-layout';

<body class="{{$root.bodyClass}}">

You could handle this in the individual controllers, or perhaps in your app.js by listening for routeChangeSuccess:

$rootScope.$on('$routeChangeSuccess', function (event, currentRoute) {
    switch(currentRoute.templateUrl) {
        case 'login.html':
        case 'register.html':
        case 'forgotpassword.html':
            $rootScope.bodyClass = 'login-layout';
            break;
        default:
            $rootScope.bodyClass = '';
            break;
    }
});

You could create a <body> directive that has add and remove class events that can be triggered throughout your app.

angular.module('myApp').directive('body', [function(){
  return {
    restrict: 'E',
    link: function(scope, element, attrs) {
      scope.$on('body:class:add', function(e, name){
        element.addClass(name);
      };
      scope.$on('body:class:remove', function(e, name){
        element.removeClass(name);
      };
      return;
    }
  };
}]);

In your app.js config block you can set the <body> class to whatever you want with $emit

## Add class
$rootScope.$emit('body:class:add', 'login-layout')

## Remove class
$rootScope.$emit('body:class:remove', 'login-layout')

it just simply uses the angular jqLite addClass() and removeClass() and also doesn't require you to tap into $element by using the directive link function which already has dom access to the element.

Even without $rootScope you can call it within your controllers with $scope.$emit('body:class:add', name) .

I'm not too sure the suggested answers work for Angular 1.4x but I think I have an easier solution.

You could easily add an activeTab property to your routes like this:

.when('/register', {
        templateUrl: 'register.html',
        controller: 'RegisterController',
        activeTab: 'register'
      })

Then in your Controller add the $route object to your $scope:

.controller('RegisterController', ['$scope', '$route', function($scope, $route){
     $scope.$route = $route;
}])

And use ng-class on your body tag:

<body ng-class="{'register-class' : $route.current.activeTab == 'register' }">
</body>

This way you can dynamically set a class on your body tag when you change routes. Hope this helps someone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM