Reputation: 191
Ok. So here is a noob question. I just started fooling around with angularjs and I was wondering if there is some sort of toggle function similar to ng-click or I have to build my own. What I want is to change the background and the font color of the body of my page, when the user checks the dark theme option.
I managed to change the color on the click function but I need it to come back to initial state when it is not checked. Any suggestions are welcome:)
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp" ng-style="myStyle">
<label><input type="checkbox" ng-click="myStyle={background:'black', color:'white'}">Dark theme</label>
<script>
app = angular.module('myApp', []);
</script>
</body>
</html>
Upvotes: 1
Views: 2459
Reputation: 1319
You'll want to add the style to the components .scss file or app.scss
.darkTheme {background:'black', color:'white'}
And then you could apply your style using the ng-class directive as Steve mentioned
<body ng-app="myApp" ng-class="{'darkTheme' : darkToggle}">
And add a model to the input
<input type="checkbox" ng-model="darkToggle">
Upvotes: 1
Reputation: 191
Working solution
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<style>
.dark-theme {
color: white;
background: black;
}
</style>
<body ng-app="myApp" ng-class="{'dark-theme': dark}">
<label><input type="checkbox" ng-model="dark">Dark theme</label>
<script>
app = angular.module('myApp', []);
</script>
</body>
</html>
Upvotes: 0
Reputation: 1953
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.
Upvotes: 3