Dynamic body class with Angular UI-Router

后端 未结 4 665
长发绾君心
长发绾君心 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:25

    This is just a version of @JeremyWeir's directive using ui-router@1.x transition hooks.

    import angular from 'angular';
    
    class RouteCssClassNamesDirective {
      constructor($transitions) {
        this.$transitions = $transitions;
        this.restrict = 'A';
      }
    
      link(scope, element, attrs) {
        this.$transitions.onSuccess({}, (trans) => {
          const fromClassNames = angular.isDefined(trans.from().data) && angular.isDefined(trans.from().data.cssClassNames) ? trans.from().data.cssClassNames : null;
          const toClassNames = angular.isDefined(trans.to().data) && angular.isDefined(trans.to().data.cssClassNames) ? trans.to().data.cssClassNames : null;
          if (fromClassNames !== toClassNames) {
            if (fromClassNames) {
              element.removeClass(fromClassNames);
            }
            if (toClassNames) {
              element.addClass(toClassNames);
            }
          }
        });
      }
    
      static create() {
        return new RouteCssClassNamesDirective(...arguments);
      }
    
    }
    
    RouteCssClassNamesDirective.create.$inject = ['$transitions'];
    
    export default angular.module('shared')
      .directive('routeCssClassNames', RouteCssClassNamesDirective.create);
    

提交回复
热议问题