Dynamic body class with Angular UI-Router

后端 未结 4 669
长发绾君心
长发绾君心 2020-12-24 03:01

I\'m trying to find an elegant way to have a custom dynamically class of the body tag that I can set easily from the ui-router configurations a

4条回答
  •  没有蜡笔的小新
    2020-12-24 03:22

    Here's a similar approach as @jmq's using state data, but implemented as a directive instead of a controller. (The nice thing about the directive is you can apply this to any arbitrary elements)

    Example Markup

    
    

    Routes Config (routes.js)

    $stateProvider
      .state('login', {
           url: "/login",
           template: 'Login',
           data : {
               cssClassnames : 'auth'
           }
      })
      .state('register', {
           url: "/register",
           template: 'Register',
           data : {
               cssClassnames : 'auth'
           }
      }).
      .state('profile', {
           url: "/profile",
           template: 'Profile'
      });
    

    Directive (routeCssClassnames.js)

    (function () {
        'use strict';
    
        angular.module('shared').directive('routeCssClassnames', routeCssClassnames);
    
        function routeCssClassnames($rootScope) {
            return {
                restrict: 'A',
                scope: {},
                link: function (scope, elem, attr, ctrl) {
    
                    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
                        var fromClassnames = angular.isDefined(fromState.data) && angular.isDefined(fromState.data.cssClassnames) ? fromState.data.cssClassnames : null;
                        var toClassnames = angular.isDefined(toState.data) && angular.isDefined(toState.data.cssClassnames) ? toState.data.cssClassnames : null;
    
                        // don't do anything if they are the same
                        if (fromClassnames != toClassnames) {
                            if (fromClassnames) {
                                elem.removeClass(fromClassnames);
                            }
    
                            if (toClassnames) {
                                elem.addClass(toClassnames);
                            }
                        }
                    });
                }
            }
        }
    }());
    

提交回复
热议问题