Load CSS Theme Dynamically on user selection in AngularJS

To implement themes in application I create multiple css files with different styles like (red, green,blue). 
 
Red.css
  1.    
  2. body  
  3. {  
  4. font-family"Source Sans Pro",Calibri,Candara,Arial,sans-serif;  
  5. font-size15px;  
  6. line-height1.42857143;  
  7. color#333333;  
  8. background-colorred;  
  9. }  
  10.    
Blue.css
  1. body  
  2. {  
  3.     font-family"Source Sans Pro",Calibri,Candara,Arial,sans-serif;  
  4.     font-size15px;  
  5.     line-height1.42857143;  
  6.     colorwheat;  
  7.     background-colorblue;  
  8. }  
Green.css
  1. body  
  2. {  
  3.     font-family"Source Sans Pro",Calibri,Candara,Arial,sans-serif;  
  4.     font-size15px;  
  5.     line-height1.42857143;  
  6.     colorchartreuse;  
  7.     background-colorgreen;  
  8. }  
Then I create an app.js file for AngularJS, in which I declare my Angular module and controller.
  1. angular.module('ThemeApp', [])  
  2.   
  3.     .controller('mainController'function ($scope) {  
  4.   
  5.         // set the default theme   
  6.         $scope.css = 'Red';  
  7.   
  8.         // create the list of themes  
  9.         $scope.bootstraps = [  
  10.           { name: 'Red', url: 'Red' },  
  11.           { name: 'Blue', url: 'Blue' },  
  12.           { name: 'Green', url: 'Green' }  
  13.         ];          
  14.   
  15.     });  
In the above code I declare a module "ThemeApp" and then attach a controller with this module. In the controller I declare an object array with all available theme that implements my application. I set one of theme by default for application for the first time.
 
Now, moving to HTML Page.
  1. <html ng-app="ThemeApp" ng-controller="mainController">  
  2.   
  3. <head>  
  4.   
  5.     <script src="Scripts/angular.min.js"></script>
  6.     <!-- pull in css based on angular -->  
  7.     <link rel="stylesheet" ng-href="{{css}}.css">   
  8.     <!-- bring in JS and angular -->  
  9.     <script src="CustomJS/app.js"></script>  

  10. </head>  
  11.   
  12. <body>  
  13.     <div >  
  14.         <form>  
  15.   
  16.             <div >  
  17.                <h1> <label>Select   Theme</label></h1>  
  18.                 <select  ng-model="css" ng-options="bootstrap.url as bootstrap.name for bootstrap in bootstraps">  
  19.                 </select>  
  20.             </div>              
  21.         </form>  
  22.     </div>    
  23. </body>  
  24. </html>  
Your output will looks like this
 


 
So, We can exactly see how it works. We are pulling our own custom css file dynamically with ng-Href directive in AngularJS.
Ebook Download
View all
Learn
View all