gpt4 book ai didi

css - 通过angularJS ng-style可变背景图像

转载 作者:行者123 更新时间:2023-11-28 11:07:14 25 4
gpt4 key购买 nike

抱歉,如果这是一个新问题。我正在尝试创建一个具有背景图像的登录页面,而我的其余页面则没有。我使用过 ng-style 但我无法让属性在页面更改时更新。在我的 index.html 中:

<body ng-app="myApp" ng-style="bodyStyle" ng-controller="bodyController">
//content
</body

body Controller :

var image="http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg";
if ($location.path() === '/login') {
$scope.bodyStyle = {background: "url(" + image + ") no-repeat center center fixed"};
} else{
$scope.bodyStyle={background: ""}
}

显然这不起作用,因为该函数只被调用一次。我试过使用 rootScope,但我似乎无法以 ng 风格使用 rootScope 属性(而且在我看来的任何地方,人们都建议不要为此目的使用 rootScope)。如何创建动态背景?如果可能的话,我也不想在我的 body 标签上使用 Controller 。

更新

我遇到的主要问题是背景图像在更改路径时不会更新。图片在 bodycontroller 中设置,登录和更改路径时不会更改。

根据我可以编写一个服务的建议,我以前使用过它们但只是通过 getter 和 setter,所以我假设我可以创建一个向 Controller 发送调用的服务?看起来像这样:

<body ng-app="myApp" ng-style="bodyStyle" ng-controller="bodyController">
//content
</body

body Controller

var image=??;
$scope.bodyStyle = {background: "url(" + image + ") no-repeat center

一些服务

 .service('backgroundService', function (image) {
var backgroundImage = image
// somhow set bodycontroller image?
});

然后在路由更改时以某种方式调用服务?我还没有找到将服务注入(inject)我的路由器配置的方法,我认为这是我需要的。

最佳答案

所以我在一些帮助下想出了一个简单的方法来做到这一点。

在 app.js 中添加:

.run(function ($rootScope, $location) {
$rootScope.$on( "$routeChangeStart", function(event, next, current) {
$rootScope.bodyClass = $location.path().replace('/', '') + '-page';
});
});

并将索引更改为:

<body ng-app="myApp" ng-class="bodyClass">

和CSS:

.login-page {
background: url("someImage") no-repeat center center fixed;
}

关于css - 通过angularJS ng-style可变背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30981593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com