1

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>

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ya, thanks, I managed to figure it out. I will post an answer with the updated solution, maybe another poor soul will need this.
1

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">

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.