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:
<button ng-click="changeStyle('colors.css')" id="pink">Brookes Pink</button><br />
<button ng-click="changeStyle('colors-lime.css')" id="lime">Brookes Lime</button><br />
<button ng-click="changeStyle('colors-muted.css')" id="muted">Muted colours</button><br />
<button ng-click="changeStyle('colors-dark.css')" id="dark">Dark colours</button>
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.
 .controller('settingsCtrl',
['$rootScope', '$scope', '$uibModal', '$routeParams', '$log', '$timeout', '$http',
    function ($rootScope, $scope, $uibModal, $routeParams, $log, $timeout, $http) {
        $scope.settings = [];
        $rootScope.filename = $.jStorage.get('myStyle', '') || 'colors';
        $scope.changeStyle = function (stylesheet) {
            $rootScope.filename = stylesheet;
            $.jStorage.set('myStyle', stylesheet, { TTL: 28800000 });
        };
    }])
I have used jStorage to store the user's preference for a stylesheet, but you could also use cookies.

No comments:

Post a Comment