【问题标题】:Changing body background color with angularjs使用 angularjs 更改正文背景颜色
【发布时间】:2014-05-04 14:38:48
【问题描述】:

我希望能够根据当前路径更改<body> 的背景颜色。

我尝试通过在路径更改时检查 $location.path() 然后使用 ng-style 指令更改背景颜色来做到这一点,但这似乎是一种 hack(并且不起作用)。

什么是更解耦的方式来实现这一点?

这是我写的代码,如果有人想看的话。

app.controller('backgroundCtrl', ['$rootScope', '$scope', '$route', '$location', function($rootScope, $scope, $route, $location){
  $rootScope.$on('$routeChangeStart', function(){

    if ($location.path() == '/'){
      $scope.backgroundStyle = {background: '#ffffff'};
    } else {
      $scope.backgroundStyle = {background: '#000000'};
    }

  });
}]);

【问题讨论】:

    标签: javascript css angularjs


    【解决方案1】:

    为了解耦样式、数据、内容等方面的这种动态变化,通常可以创建另一个包含接口(自定义提供程序)的 Angular 模块,该模块可以让您在配置级别之前和之后访问这些更改.这是plunker,提供了我将在下面讨论的内容。

    对于这个答案,我创建了一个带有provider RouteData 的小模块(route-data.js),它公开 两种功能配置:

    applyConfig() - 分配要在 RouteData 服务中访问的设置。 hookToRootScope() - 将 RouteData 服务挂接到 $rootScope 中,从而使其可用于所有要创建的子范围和整个应用程序。

    RouteData 提供程序有一个RouteData() 服务,它提供对设置和获取RouteData 设置的方法的访问,这些设置将在$routeProvider 配置中提供。

    (如果您不熟悉提供商和服务,请阅读更多相关信息here

    (如果您不熟悉config()run() 方法,可以在here 中阅读更多内容)

    route-data.js

    angular.module('RouteData', []).
    
    provider('RouteData', function () {
      var settings = {};
      var hookToRootScope = false;
    
      this.applyConfig = function(newSettings) {
        settings = newSettings;
      };
    
      this.hookToRootScope = function(enableRootScopeHook) {
        hookToRootScope = enableRootScopeHook;
      };
    
      function RouteData() {
    
        this.set = function(index, value) {
          settings[index] = value;
        };
    
        this.get = function(index) {
          if(settings.hasOwnProperty(index)) {
            return settings[index];
          } else {
            console.log('RouteData: Attempt to access a propery that has not been set');
          }
        };
    
        this.isHookedToRootSope = function() {
          return hookToRootScope;
        };
      }
    
      this.$get = function() {
          return new RouteData();
      };
    }).
    
    run(['$location', '$rootScope', 'RouteData', function($location, $rootScope, RouteData) {
      if(RouteData.isHookedToRootSope()) {
        $rootScope.RouteData = RouteData;
      }
    
      $rootScope.$on('$routeChangeStart', function(event, current, previous) {
        var route = current.$$route;
        if(typeof(route) !== 'undefined' && typeof(route['RouteData']) !== 'undefined') {
          var data = route['RouteData'];
          for(var index in data)
            RouteData.set(index, data[index]);
        } 
      });
    }]);
    

    下面的脚本展示了如何通过在配置级别注入 RouteDataProvider 来使用上面的 RouteData 模块,并通过RouteDataProvider.applyConfig() 应用默认配置,例如bodyStyle,您还可以在应用程序完全运行之前添加更多设置。通过将RouteDataProvider.hookToRootScope() 设置为true 将其连接到$rootScope。最后,附加数据,RouteData,例如

    RouteData: {
          bodyStyle: {
            'background-color': 'green'
          }
        }
    

    由 $routeProvider 发送并由 RouteData 模块中定义的 run() 方法处理,该方法初始化应用程序中要访问的 RouteData 服务的设置。

    script.js

    angular.module('app', ['ngRoute', 'RouteData']).
    
    config(['$routeProvider', 'RouteDataProvider', function($routeProvider, RouteDataProvider) {
      RouteDataProvider.applyConfig({
        bodyStyle: {
          'background-color': 'white'
        }
      });
    
      RouteDataProvider.hookToRootScope(true);
    
      $routeProvider.when('/landing', {
        RouteData: {
          bodyStyle: {
            'background-color': 'green'
          }
        },
        templateUrl: 'landing.html',
        controller: 'LandingController'  
      }).when('/login', {
        RouteData: {
         bodyStyle: {
             'background-color': 'gray',
             padding: '10px',
             border: '5px solid black',
             'border-radius': '1px solid black'
         }
        },
        templateUrl: 'login.html',
        controller: 'LoginController'
      }).otherwise({
        redirectTo: '/landing'
      });
    
    }]).
    
    controller('LoginController', ['$scope', function($scope) {
    
    }]).
    
    controller('LandingController', ['$scope', function($scope) {
    
    }]);
    

    所以要添加到您的索引页面或任何其他页面中的最后一段代码将是这样的。

    index.html的一部分

    <body ng-style="RouteData.get('bodyStyle')"> 
        <a href="#/landing">Landing</a> | 
        <a href="#/login">Login</a>
        <div ng-view></div>
    </body>
    

    【讨论】:

    • 非常感谢您的详细回答。我很感激
    • 有一个错字导致它崩溃。 this.hookToRootScope 应该是 this.hookToRootScope
    【解决方案2】:

    设置正文样式的一种方法是将ng-view 添加为正文属性,然后使用ng-classng-style(迄今为止我没有使用任何其他选项)。

    例如:

    <!doctype html>
    <html ng-app="my-app">
      <head>
        <title>My Site</title>
        <script src="angular/angular.js"></script>
      </head>
      <body ng-class="{login:loginBody}" ng-view>
        <script src="my-app.js"></script>
      </body>
    </html>
    

    在本例中,login 类仅在 loginBody 是当前范围内的真值(在登录控制器中设置)时应用于正文。

    这比@ryeballar 提供的方法灵活得多。在某些情况下可能就足够了。

    【讨论】:

      【解决方案3】:

      我注意到当我导航到另一个页面而不重新加载页面时,背景颜色仍然存在,所以我正在这样做(我正在使用 angular ui-router):

      在配置中:

      $stateProvider.state('app.login',{
                  url: '/login',
                  onExit: function($rootScope){
                      $rootScope.bodyClass = 'body-one';
                  },
                 templateUrl: 'ng/templates/auth/login-page-one.html',
                  controller: function($rootScope){
                      $rootScope.bodyClass = 'body-two';
                  }
              })
      
              .state('app.signup',{
                  url: '/signup',
                  onExit: function($rootScope){
                      $rootScope.bodyClass = 'body-one';
                  },
                  templateUrl: 'ng/templates/auth/signup-page-one.html',
                  controller: function($rootScope){
                      $rootScope.bodyClass = 'body-two';
                  }
              });
      

      在模板中

      <body class="{{bodyClass ? bodyClass : 'body-one'}}">
      

      在 CSS 中:

      .body-one{
          margin-top: 50px;
          background: #f0f4fb;
      }
      
      .body-two{
          margin: 0;
          padding: 0;
          background: #2e9fff;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-16
        • 2013-02-17
        • 1970-01-01
        • 1970-01-01
        • 2012-12-24
        • 2018-12-25
        相关资源
        最近更新 更多