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

后端 未结 4 1911
一生所求
一生所求 2020-12-15 01:59

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 H

4条回答
  •  悲&欢浪女
    2020-12-15 02:50

    UPDATED: Here is the solution to inject(load) a specific CSS using the $routeProvider.

    The solution described below is an alternative to apply different classes and page title based on the route which could be used in other situations.

    For each route I've created a new key called 'bodyClass' and 'title' (but you could called anything you like it) and it looks like this:

    'use strict';
    var myApp = angular.module('myApp', 'ngResource'])
    .config(function ($routeProvider) {
    
    myApp.siteName = 'My Cool App';
    
    $routeProvider
        .when('/home', {
         title:'Home - ' + myApp.siteName,
         bodyClass: 'home',
         templateUrl: 'views/home.html',
         controler: 'bmsHomeCtrl'
        })
        .when('/contact', {
          title:'Contact - ' + myApp.siteName,
          bodyClass: 'contact',
          templateUrl: 'views/contact.html',
          controler: 'bmsContactCtrl'
        })
        .otherwise({
          redirectTo: '/home'
        });
    });
    

    Then for each $routeChangeSuccess event I change the </code> of the page and also the class of the <code><body></code>.</p> <pre><code>myApp.run(['$location', '$rootScope', function($location, $rootScope) { $rootScope.$on('$routeChangeSuccess', function (event, current, previous) { if (current.$$route) { $rootScope.title = current.$$route.title; $rootScope.bodyClass = current.$$route.bodyClass; } }); }]); </code></pre> <p>You put the code above on the same main <strong>app.js</strong> (for example) file.</p> <p>On my index.html page, which renders the views, I have the following codes to pick up the title and class:</p> <pre><code><title>{{ title }}

    So if i visit the home page of my application the title tag will be

     Home - My Cool App
    

    and the body tag will be

    
    

    It's working like a charm.

    I know this solution doesn't load a CSS file, but you could put those styles inside a '.contact' class that is applied only when you hit a specific route.

    Not sure if solves your problem but I hope that helps or at least point you on the right direction.

提交回复
热议问题