0

I'm trying to load specific CSS file using AngularJS controller.

HTML code looks like

<html lang="en" ng-app="CPCplusLunchLink" ng-controller="mainController">
<head>
    <meta charset="UTF-8">
    <script src="js/lib/angularjs/angular.min.js"></script>
    <script src="js/lib/angularjs/angular-route.min.js"></script>
    <script src="js/app.js"></script>
    <script src="js/controllers/main.js"></script>
    <script src="js/controllers/events.js"></script>
    <script src="js/services/events.js"></script>
    <link rel="stylesheet" ng-href="css/{{ css }}.css">

app.js related part

    .when('/', {
        templateUrl: 'views/home.html',
              controller: 'EventsController'
    })

mainContorller

myApp.controller('mainController', ['$scope', function($scope){


    // set the default css
    $scope.css = 'style';

}]);

and controller where I have set value for the CSS

myApp.controller('EventsController', ['$scope','events','$rootScope', function($scope, events, $rootScope){

// set dedicated CSS
$rootScope.css = 'style2';

    events.then(function(data) {
        $scope.eventsList = data.evets;

        console.log($scope.eventsList);
    });

}]);

but I'm not able to change default CSS value based on loaded controller.

Any clue what I have missed?

JackTheKnife
  • 3,795
  • 8
  • 57
  • 117
  • 1
    Maybe try using ng-src. But I dont think u can load css like this.Check out https://stackoverflow.com/questions/17695156/angular-js-load-css-and-js-files-dynamically – Vivz Aug 11 '17 at 14:18
  • @Vivz I have tried to follow http://www.c-sharpcorner.com/blogs/load-css-theme-dynamically-on-user-selection-in-angularjs122 and https://scotch.io/tutorials/use-angularjs-and-nghref-to-grab-css-dynamically – JackTheKnife Aug 11 '17 at 14:21
  • I just went through it and realized that you have to let angular know about the controller before you place the css – Vivz Aug 11 '17 at 14:24

1 Answers1

2

You have to let angular know about the dynamic CSS variable which is defined inside the controller. So you have to define the controller on HTML tag

<html lang="en" ng-app="myApp" ng-controller="EventsController">
Vivz
  • 6,625
  • 2
  • 17
  • 33
  • 1
    yep, example just for that here http://www.c-sharpcorner.com/blogs/load-css-theme-dynamically-on-user-selection-in-angularjs122 – bresleveloper Aug 11 '17 at 14:26
  • @viz CSS I want to change using EventsController only for that particular view (home page only) and have it set to default for other views – JackTheKnife Aug 11 '17 at 14:28
  • Do you have a main controller apart from the partial ones? Try setting the variable on $rootScope or on $scope.$parent – Vivz Aug 11 '17 at 14:29
  • @Viz No, unfortunately I don't. I will check that option and report back. – JackTheKnife Aug 11 '17 at 14:50
  • OK. I think I need to user `$rootScope` in both controllers and then do `$rootScope.$apply();` in my `EventsController` to bind it – JackTheKnife Aug 11 '17 at 15:53