Search code examples
javascriptcssangularjsngrouteng-style

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


I am new to angular and ngroute and am trying to use ng-style to have a different image background for each page of a website. Currently it sets the background of all the site's pages, even when I have different controller scope image urls.

My html is like this:

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

My script: 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...

Would I be better off going about doing this with ui-router?


Solution

  • The beter strategy would be to not do this in JavaScript but move all the styles to your css. You can acheive that by adding class using $scope variable and define those classes in css:

    Controller

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

    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"
    }