How to append a stylesheet to <head> in AngularJS $routeProvider?

user883807 picture user883807 · Aug 28, 2013 · Viewed 24.9k times · Source

I want to load a specific CSS file only when a user accesses the contact.html view on my AngularJS app/site. I found this answer which almost made sense to me How to include view/partial specific styling in AngularJS The accepted answer by charlietfl reads :

Could append a new stylesheet to head within $routeProvider. For simplicity am using a string but could create new link element also, or create a service for stylesheets

/* check if already exists first - note ID used on link element*/
/* could also track within scope object*/
if( !angular.element('link#myViewName').length){
    angular.element('head').append('<link id="myViewName" href="myViewName.css" rel="stylesheet">');
}

Biggest benefit of prelaoding in page is any background images will already exist, and less lieklyhood of FOUC

The problem is that I do not know exactly where in my $routeProvider to add the code. charlietfl mentions where to put it in a comment which reads

not if the when for the route hasn't been called. Can put this code in controller callback of when within the routeProvider, or perhaps within resolve callback which likely triggers sooner

I have modified my $routeProvider following the advice. I added a resolve in the object following .when('/contact'. Here is my code

angular.module('maxmythicApp', ['ngResponsiveImages'])
  .config(function ($locationProvider, $routeProvider) {
    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix = '!';
    $routeProvider
      .when('/', {
        templateUrl: '/views/design.html',
        controller: 'MainCtrl'
      })
      .when('/design', {
        templateUrl: '/views/design.html',
        controller: 'MainCtrl'
      })
      .when('/about', {
        templateUrl: '/views/about.html',
        controller: 'MainCtrl'
      })
      .when('/contact', {
        templateUrl: '/views/contact.html',
        controller: 'MainCtrl',
        resolve: 
          if( !angular.element('link#myViewName').length){
            angular.element('head').append('<link id="myViewName" href="myViewName.css" rel="stylesheet">');
          }
      })
      .otherwise({
        redirectTo: '/'
      });
  });

Would this work?

Answer

Gabriel picture Gabriel · Oct 8, 2013

I made a service for it.

Important part of the code :

var head = angular.element(document.querySelector('head')); // TO make the code IE < 8 compatible, include jQuery in your page and replace "angular.element(document.querySelector('head'))" by "angular.element('head')"

if(head.scope().injectedStylesheets === undefined)
{
    head.scope().injectedStylesheets = [];
    head.append($compile("<link data-ng-repeat='stylesheet in injectedStylesheets' data-ng-href='{{stylesheet.href}}' rel='stylesheet' />")(scope)); // Found here : http://stackoverflow.com/a/11913182/1662766
}

head.scope().injectedStylesheets.push({href: "/url/to/style.css"});

Full code in Github : https://github.com/Yappli/angular-css-injector)