Angular body 标签上的 ng-style 用于不同的页面背景?

Angular ng-style on body tag for different page backgrounds?

我是 angular 和 ngroute 的新手,我正在尝试使用 ng-style 为网站的每个页面设置不同的图像背景。目前它设置所有网站页面的背景,即使我有不同的控制器范围图像 url。

我的html是这样的:

<body ng-controller="mainController" ng-style="bodyStyles">
...
   <div id="main">
      <div ng-view></div>
</body>

我的脚本: var angVenture = angular.module('angVenture', ['ngRoute']);

// configure routes
angVenture.config(function($routeProvider, $locationProvider) {
    $routeProvider

        // route for the index page
        .when('/home', {
            templateUrl : 'pages/home.html',
            controller  : 'mainController'
        })

        // route for the about page
        .when('/about', {
            templateUrl : 'pages/about.html',
            controller  : 'aboutController'
        })

 ... more routes.....      

// create the controller
angVenture.controller('mainController', function($scope) {
    // create a message to display in our view
    $scope.message = 'home page';
    $scope.bodyStyles ={
        "background": "url(../images/someimage.jpg) no-repeat center center fixed", 
        "-webkit-background-size": "cover",
        "-moz-background-size": "cover",
        "-o-background-size": "cover",
        "background-size": "cover"
    }
});

angVenture.controller('aboutController', function($scope) {
    $scope.message = 'another page.';
});

....more controllers for different pages...

我最好还是用 ui-router 做这个吗?

更好的策略是不在 JavaScript 中执行此操作,而是将所有样式移至您的 css。您可以通过使用 $scope 变量添加 class 并在 css:

中定义那些 classes 来实现

控制器

angVenture.controller('mainController', function($scope) {
  // create a message to display in our view
  $scope.message = 'home page';
  $scope.bodyClass = 'main-view';
});

查看

<body ng-controller="mainController" ng-class="bodyClass">

CSS

.main-view {
  "background": "url(../images/someimage.jpg) no-repeat center center fixed", 
  "-webkit-background-size": "cover",
  "-moz-background-size": "cover",
  "-o-background-size": "cover",
  "background-size": "cover"
}

试试这个

angVenture.controller('mainController', function($scope, $location) {
      // create a message to display in our view
        var classObject = {"/home":"../images/someimage1.jpg", "/about": "../images/someimage1.jpg" };
        $scope.message = 'home page';
        $scope.imageName = classObject[$location.path()];
    });

CSS

.main-view {

  "-webkit-background-size": "cover",
  "-moz-background-size": "cover",
  "-o-background-size": "cover",
  "background-size": "cover"
}

HTML

<body ng-controller="mainController" class="main-view" styel=""background": "url({{imageName}}) no-repeat center center fixed"">