[英]How to set body attribute in css using angularjs?
我正在使用設置頁面的背景圖像:
body {
background: url(http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
text-align: center;
}
我想從控制器中的范圍變量讀取屬性,如下所示:
$scope.image="http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg"
如何在.html頁面中設置此CSS主體屬性? 在jQuery中,我可以使用.css()。 我可以使用angulalJs做類似的事情嗎? http://docs.angularjs.org/guide/dev_guide.templates.css-styling似乎沒有詳細說明?
我正在嘗試這種提琴,但不起作用:
http://jsfiddle.net/U3pVM/3015/
小提琴代碼:
<body ng-style="getBodyStyle()">
</body>
$scope.getBodyStyle = function () {
return {background: "url(http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg) no-repeat center center fixed;"};
};
在執行任何操作之前,您需要一個應用程序和控制器-您的JSFiddle失敗了,因為您沒有控制器,而且您從未定義$ scope。
您可以在控制器中創建一個名為$ scope.bodyStyle的$ scope變量,如下所示:
app.controller('MainCtrl', function($scope) {
$scope.bodyStyle = {background: "url(http://momentumbooks.com.au/wp- content/uploads/2013/06/space.jpg) no-repeat center center fixed"};
});
然后像這樣在標記中注冊應用程序和控制器:
<html ng-app="plunker">
<body ng-controller="MainCtrl" ng-style="bodyStyle">
Demo text
</body>
</html>
我做了一個Plunkr顯示整個應用程序,因為的jsfiddle是角痛。
與常規的JS或JQuery相比,Angular需要更多的協同工作-開始時可能會令人困惑,因此我建議從AngularJS種子應用開始 。
您提到要從$ scope變量獲取背景圖像。 您可以這樣做:
app.controller('MainCtrl', function($scope) {
$scope.image="http://momentumbooks.com.au/wp-content/uploads/2013/06/space.jpg";
$scope.bodyStyle = {background: "url(" + $scope.image + ") no-repeat center center fixed"};
});
您可以執行以下操作:
<body ng-style="getBodyStyle()">`
和
$scope.getBodyStyle = function () {
return {background: myData};
};
其實,我所做的是調用API以在狀態resolve
返回圖像URL:
resolve: {
'image': ['$http', function($http) {
return $http.get('/api/image');
}]
}
API返回JSON:
res.json({url: 'someUrl'});
然后將其注入控制器,然后在控制器中調用:
angular.element('body').css('background-image', 'url(\'' + image.data.url + '\')');
這對我來說似乎很干凈,因為它不需要將$scope
注入到控制器中,這在最近成為了禁忌。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.