用angularjs改变身体背景颜色

时间:2014-03-26 09:38:58

标签: javascript css angularjs

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

我尝试通过在路径更改后检查$ location.path(),然后使用ng-style指令更改背景颜色来执行此操作,但这看起来像是一个黑客(并且无效)。< / p>

实现这一目标会有什么更加脱钩的方式?

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

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

  });
}]);

3 个答案:

答案 0 :(得分:12)

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

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

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

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

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

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

<强>路由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并使用bodyStyle通过RouteDataProvider.applyConfig()应用默认配置来使用上面的RouteData模块,您还可以在应用程序之前添加更多设置完全正常运行。通过将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>

答案 1 :(得分:4)

设置正文的一种方法是添加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提供的方法灵活得多。在某些情况下,这可能就足够了。

答案 2 :(得分:0)

我注意到当我导航到没有页面重新加载的其他页面时,背景颜色仍然存在,所以我这样做(我使用的是角度 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;
}