Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS switch css theme on user selection

I downloaded the themes from bootswatch and I'm trying to allow the user to switch the theme. When the theme is switched all the bootstap css temporarily goes away until the new theme is loaded. How can I prevent the change until the css is loaded or switch back to the default theme until the new one is loaded?

index.ejs (in the head)

<link rel="stylesheet" href="/external/bootstrap/css/bootstrap_yeti.min.css"
      ng-if="myTheme == ''">
<link rel="stylesheet" ng-href="/external/bootstrap/css/bootstrap_{{myTheme}}.min.css"
      ng-if="myTheme != ''">

Selection

<select class="form-control"
        id="theme"
        name="theme"
        ng-model="theme"
        ng-change="newTheme()">
  <option value="" disabled>Select Theme</option>
  <option ng-repeat="(key, val) in availableThemes" value="{{val}}">{{key}}</option>
</select>

controller on index

$scope.myTheme = '';
$rootScope.$watch('myTheme', function(value) {
  if (value != undefined) {
    $scope.myTheme = value;
  }
});

controller for selection

$scope.availableThemes = {
  Cerulean: 'cerulean',
  Cosmo:    'cosmo',
  Yeti:     'yeti'
};
$scope.newTheme = function() {
  console.log($scope.theme);
  if ($scope.theme != undefined) {
    $rootScope.myTheme = $scope.theme;
  }
}

Any help is appreciated! Thank you

like image 313
Elementary Avatar asked Nov 30 '22 11:11

Elementary


1 Answers

I find it better to keep it simple, and there's no need to pre-load all the themes like other have suggested.

Stick to a single tag with ng-href:

<link rel="stylesheet" ng-href="/external/bootstrap/css/bootstrap_{{myTheme}}.min.css">

And initialize myVar in your scope to "yeti" in the index controller:

$scope.myTheme = 'yeti';
$rootScope.$watch('myTheme', function(value) {
  if (value != undefined) {
    $scope.myTheme = value;
  }
});

The rest stays the same.

like image 81
Josep Sayol Avatar answered Dec 09 '22 20:12

Josep Sayol