如何根据网址或路由更改应用程序的背景图像?

时间:2013-07-26 04:19:14

标签: angularjs

我想根据网址更改应用程序的背景图片(Html Body)。而我只想在angularJS中做:)

例如:

1)如果用户访问这样的网址,

www.domain.com/的厂景

显示贝娄图像

enter image description here

2)如果用户访问网址   www.domain.com/view2

我想要显示其他图片

enter image description here

app.js

  var app = angular.module('app', []);

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
    $routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
    $routeProvider.otherwise({redirectTo: '/view1'});
  }])

app.config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode(true);
}]);;

Controler.js

 app.controller('MyCtrl1',function($scope){
    $scope.viewBackground="body"
    console.log($scope.viewBackground);
})

app.controller('MyCtrl2',function($scope){
    $scope.viewBackground="profile"
})

在部分html中,我只是这样做

    <div class="span12">


            <p>

           {{$scope.viewBackground}}zxz
            </p>

    </div>

但是有些原因我无法获得 viewBackground 属性值的值。

2 个答案:

答案 0 :(得分:1)

我不确定我是否正确理解你,但我希望如此。 你有2个选择。

首先 - 为每个页面使用不同的控制器 view1 view2 。 并在页面上使用ng-class指令:

<强> HTML

<!-- "page" View 1 -->
<div ng-controller="View1Ctrl">
    <div ng-class="viewBackground"> View 1 </div> 
</div>

<!-- "page" View 2 -->
<div ng-controller="View2Ctrl">
    <div ng-class="viewBackground"> View 2 </div> 
</div>

<强> JS

var app = angular.module('app', []);

function View1Ctrl($scope) {
    $scope.viewBackground = "background-small"
}    

function View2Ctrl($scope) {
    $scope.viewBackground = "background-big"
}    

CSS

.background-small{
    height:200px;
    width:200px;
    background: url('...img1...');
}

.background-big{
    height:400px;
    width:400px;
        background: url('...img2...');
}

第二个选项 - 使用 .run 块,您将在其中添加一些逻辑来更改bg-image,但这是一个不好的选择

答案 1 :(得分:0)

如果您的控制器可以检查$ routeParams参数,然后设置范围变量来控制背景图像。

function announcements_detail_controller($scope, $rootScope, $routeParams, $http, $location)
{  //console.log($routeParams);
   $scope.css_class_for_background_image = 'xxxx';//

}