javascript 使用 angularjs 更改正文背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22656847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:32:00  来源:igfitidea点击:

Changing body background color with angularjs

javascriptcssangularjs

提问by user1215653

I want to be able to change the background color of <body>depending on what the current path is.

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

I tried doing it by checking $location.path() whenever the path was changed and then using the ng-styledirective to change the background color but this seems like a hack (and didn't work).

我尝试通过检查 $location.path() 每当路径更改然后使用ng-style指令来更改背景颜色来做到这一点,但这似乎是一个黑客(并且没有用)。

What would be a more decoupled way to achieve this?

实现这一目标的更加解耦的方法是什么?

Here's the code I wrote if anyone wants to see it.

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

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'};
    }

  });
}]);

回答by ryeballar

To decouple such a dynamic change in style, data, content and etc., it is often practical to create another angular module that contains an interface(Custom Provider) that can give you access to these changes before and after the configuration level. Here is a plunkerto provide a view of what I'll be discussing below.

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

For this answer, I have created a small module(route-data.js) with a provider, RouteData, which exposes two function configurations:

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

applyConfig()- assigns settings to be accessed in the RouteData service. hookToRootScope()- hooks the RouteData service in the $rootScopehence making it available to all child scopes to be created and the entire application.

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

The RouteData provider has a RouteData()service that provides access to methods which sets and gets RouteDatasettings that will be provided in the $routeProviderconfiguration.

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

(If you're not familiar with providers and services, read more about it here)

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

(If you're not familiar with the config()and run()methods, you can read more in here)

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

route-data.js

路由数据.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]);
    } 
  });
}]);

The script below shows how to use the RouteData Module above via injecting the RouteDataProvider in the configuration level and apply default configurations such as the bodyStylevia RouteDataProvider.applyConfig(), you may also add more settings before the application is fully running. Hook it up in the $rootScope by setting RouteDataProvider.hookToRootScope()to true. Lastly, appending data, RouteDatae.g.

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

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

to be sent in by the $routeProvider and processed by the run()method defined in the RouteData module which initializes the settings for the RouteData services to be accessed in the application.

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

script.js

脚本.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) {

}]);

So the final piece of code to be added in your index page or any other page would be something like this.

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

A portion of index.html

一部分 index.html

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

回答by Eric Platon

One way to style the body is to add ng-viewas a body attribute, then use ng-classor ng-style(I did not use any other option to date).

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

For example:

例如:

<!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>

In this example, the loginclass is applied to the body only when loginBodyis a true value in the current scope, set in a login controller.

在此示例中,login仅当loginBody在登录控制器中设置的当前范围内为真值时,才将类应用于主体。

This is much less flexible than the approach offered by @ryeballar. It may just be enough in some cases.

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

回答by Emeka Mbah

I noticed that when I navigate to another page without page reload background color still remains, so I am doing this (I am using angular ui-router):

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

In config:

在配置中:

$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';
            }
        });

In the Template

在模板中

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

In CSS:

在 CSS 中:

.body-one{
    margin-top: 50px;
    background: #f0f4fb;
}

.body-two{
    margin: 0;
    padding: 0;
    background: #2e9fff;
}