Changing body background color with angularjs
To decouple such a dynamic change in style, data, content and etc., it is often practical to create another angular module that contains an interface(Custom Provider) that can give you access to these changes before and after the configuration level. Here is a plunker to provide a view of what I'll be discussing below.
For this answer, I have created a small module(route-data.js) with a provider
, RouteData, which exposes
two function configurations:
applyConfig()
- assigns settings to be accessed in the RouteData service.hookToRootScope()
- hooks the RouteData service in the $rootScope
hence making it available to all child scopes to be created and the entire application.
The RouteData provider has a RouteData()
service that provides access to methods which sets and gets RouteData
settings that will be provided in the $routeProvider
configuration.
(If you're not familiar with providers and services, read more about it here)
(If you're not familiar with the config()
and run()
methods, you can read more in here)
route-data.js
angular.module('RouteData', []).
provider('RouteData', function () {
var settings = {};
var hookToRootScope = false;
this.applyConfig = function(newSettings) {
settings = newSettings;
};
this.hookToRootScope = function(enableRootScopeHook) {
hookToRootScope = enableRootScopeHook;
};
function RouteData() {
this.set = function(index, value) {
settings[index] = value;
};
this.get = function(index) {
if(settings.hasOwnProperty(index)) {
return settings[index];
} else {
console.log('RouteData: Attempt to access a propery that has not been set');
}
};
this.isHookedToRootSope = function() {
return hookToRootScope;
};
}
this.$get = function() {
return new RouteData();
};
}).
run(['$location', '$rootScope', 'RouteData', function($location, $rootScope, RouteData) {
if(RouteData.isHookedToRootSope()) {
$rootScope.RouteData = RouteData;
}
$rootScope.$on('$routeChangeStart', function(event, current, previous) {
var route = current.$$route;
if(typeof(route) !== 'undefined' && typeof(route['RouteData']) !== 'undefined') {
var data = route['RouteData'];
for(var index in data)
RouteData.set(index, data[index]);
}
});
}]);
The script below shows how to use the RouteData Module above via injecting the RouteDataProvider in the configuration level and apply default configurations such as the bodyStyle
via RouteDataProvider.applyConfig()
, you may also add more settings before the application is fully running. Hook it up in the $rootScope by setting RouteDataProvider.hookToRootScope()
to true. Lastly, appending data, RouteData
e.g.
RouteData: {
bodyStyle: {
'background-color': 'green'
}
}
to be sent in by the $routeProvider and processed by the run()
method defined in the RouteData module which initializes the settings for the RouteData services to be accessed in the application.
script.js
angular.module('app', ['ngRoute', 'RouteData']).
config(['$routeProvider', 'RouteDataProvider', function($routeProvider, RouteDataProvider) {
RouteDataProvider.applyConfig({
bodyStyle: {
'background-color': 'white'
}
});
RouteDataProvider.hookToRootScope(true);
$routeProvider.when('/landing', {
RouteData: {
bodyStyle: {
'background-color': 'green'
}
},
templateUrl: 'landing.html',
controller: 'LandingController'
}).when('/login', {
RouteData: {
bodyStyle: {
'background-color': 'gray',
padding: '10px',
border: '5px solid black',
'border-radius': '1px solid black'
}
},
templateUrl: 'login.html',
controller: 'LoginController'
}).otherwise({
redirectTo: '/landing'
});
}]).
controller('LoginController', ['$scope', function($scope) {
}]).
controller('LandingController', ['$scope', function($scope) {
}]);
So the final piece of code to be added in your index page or any other page would be something like this.
A portion of index.html
<body ng-style="RouteData.get('bodyStyle')">
<a href="#/landing">Landing</a> |
<a href="#/login">Login</a>
<div ng-view></div>
</body>
Set different body background for different pages when using AngularJS template and ui-router
In a global controller (which is applied to either <html>
or <body>
tag), register an event:
myApp.controller('GlobalCtrl', function($scope) {
// Event listener for state change.
$scope.$on('$stateChangeStart', function(event, toState, toParams) {
$scope.bodyClass = toState.name + '-page';
});
});
Now, in your HTML:
<body class="{{bodyClass}} foo bar" ng-controller="GlobalCtrl">
<!-- your content -->
</body>
Now, in your CSS:
body.login-page {
background: green;
}
body.home-page {
background: red;
}
Change background and font color with angularjs
You can use ng-class to apply new classes to elements. The docs are here: https://docs.angularjs.org/api/ng/directive/ngClass
I've done something similar in an app of my own, where selecting a theme from the options page applies a new class to the main content section of each page. I don't have the code available right now but I can post it in later if you would like.
How to change the background color of the outermost body tag with Angular
There is an easier way in your component
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor() {
document.body.style.background = 'rgba(0, 0, 0, .6)';
}
}
Or with simple CSS in your src/styles.css
body {
background: whatever;
}
How to change background color of an item based on the click in AngularJs
var app = angular.module("ap",[]);
app.controller("con",function($scope){ $scope.changeIndex = function(index){ $scope.selected = index; }});
.blue{ color: blue;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><body ng-app="ap" ng-controller="con"><div ng-repeat="n in [10, 20, 30, 40] track by $index"> <div ng-class="{blue: selected==$index}" ng-click="changeIndex($index)">{{n}}</div> </div></body>
How to change whole page background-color in Angular
You can do this from any of your component. For example:
export class AppComponent implements AfterViewInit {
constructor(private elementRef: ElementRef) {}
ngAfterViewInit() {
this.elementRef.nativeElement.ownerDocument
.body.style.backgroundColor = 'yourColor';
}
}
By using this.elementRef.nativeElement.ownerDocument
, you can access the window.document
object without violating any angular convention. Of course, you can directly access the document
object using window.document
but, I think it would be better to access it through ElementRef
.
How to change body background image by clicking a button in Angular Js?
You have a problem with the syntax. You need to wrap background-image
key in quotes, otherwise it's not a valid identifier. It works with background
because having nothing but alpha characters, it doesn't require quotes.
<input type="button" class="bg numbers" ng-click="myStyle={'background-image': 'url(../images/count2.png)'}">
Then it will work properly:
angular.module('demo', [])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<body ng-app="demo" ng-style="myStyle">
<input type="button" class="bg numbers" ng-click="myStyle={'background-image': 'url(http://subtlepatterns2015.subtlepatterns.netdna-cdn.com/patterns/dark_embroidery.png)'}" value="Set background">
</body>
change background color with angularjs
If you are using ng-repeat then I would recommend ng-class.
<h1 ng-click="isReadClick(q.id)" ng-class="q.isRead ? 'green' : 'red'"> {{q.title}}</h1>
In the example, if q.isRead
value is a true then set class green
else set class red
.
How to set background color for a div dynamically in angular?
You can use ng-style to achieve this
<div ng-style="{'background-color':vitalItem.value.color}" >
Related Topics
How to Change the Id of a HTML Element with JavaScript
CSS Textarea That Expands as You Type Text
Passing Mouse Clicks Through an Overlaying Element <Div>
Change Iframe Src by Clicking a Link
Highcharts - Issue About Full Chart Width
D3 Bar Graph Example Not Working Locally
How to Detect When a New Element Has Been Added to the Document in Jquery
How to Add a List of Images to the Document from an Array of Urls
Issue with Comparing Two Numbers in JavaScript
Find Selected Item in Datalist in HTML
Canvas.Todataurl() Security Error the Operation Is Insecure
Disable Spaces in Input, and Allow Back Arrow
How to Display Selected Image Without Sending Data to Server
Make a <Br> Instead of <Div></Div> by Pressing Enter on a Contenteditable
Why Doesn't JavaScript Newlines Work Inside HTML
Manually Triggering the Iphone/Ipad/Ipod Keyboard from JavaScript