Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用angularjs更改身体背景色_Javascript_Css_Angularjs - Fatal编程技术网

Javascript 使用angularjs更改身体背景色

Javascript 使用angularjs更改身体背景色,javascript,css,angularjs,Javascript,Css,Angularjs,我希望能够根据当前路径更改的背景色 我尝试通过在路径更改时检查$location.path(),然后使用ng style指令更改背景色来完成此操作,但这似乎是一种黑客行为(而且不起作用) 要实现这一点,哪种方法更为解耦 如果有人想看,这是我写的代码 app.controller('backgroundCtrl', ['$rootScope', '$scope', '$route', '$location', function($rootScope, $scope, $route, $locati

我希望能够根据当前路径更改
的背景色

我尝试通过在路径更改时检查$location.path(),然后使用
ng style
指令更改背景色来完成此操作,但这似乎是一种黑客行为(而且不起作用)

要实现这一点,哪种方法更为解耦

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

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

  });
}]);

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

对于这个问题,我创建了一个小模块(route data.js),其中包含一个
提供者
,RouteData,它公开了 两种功能配置:

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

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

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

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

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

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

RouteData: {
      bodyStyle: {
        'background-color': 'green'
      }
    }
由$routeProvider发送,并由RoutedData模块中定义的
run()
方法处理,该模块初始化应用程序中要访问的RoutedData服务的设置

script.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]);
    } 
  });
}]);
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>

| 

设置主体样式的一种方法是添加
ng视图
作为主体属性,然后使用
ng类
ng样式
(到目前为止,我没有使用任何其他选项)

例如:

<!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
是当前范围内的真值(在登录控制器中设置)时才应用于主体


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

我注意到,当我导航到另一个页面而不重新加载页面时,背景颜色仍然保留,因此我正在这样做(我使用的是angularui 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-one{
    margin-top: 50px;
    background: #f0f4fb;
}

.body-two{
    margin: 0;
    padding: 0;
    background: #2e9fff;
}
在模板中

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

非常感谢您的详细回答。我很感激这是一个打字错误导致了这个崩溃。this.hookToRootScope应该是this.hookToRootScope