Pages

Friday, 23 December 2016

AngularJS style switcher

It's often the case that you want to provide more than one CSS stylesheet for your app or website. You can do this by including a style switching function in your app. Here's how to do it in AngularJS.

In the HTML, create a button for each stylesheet that you want to switch between, and pass in the filename of the stylesheet as a variable:

You will also need to put the ng-app attribute in the <html> element, and an angular variable in the path to the stylesheet:

<html ng-app="myApp">

<head>

<link rel="stylesheet" data-ng-href="css/{{ filename }}" />

In the Angular (app.js), create a settings controller with a changeStyle function. Note that the stylesheet variable is a rootscope variable because the variable we are changing is in the <head>, outside of any block governed by a controller.