How to include view/partial specific styling in AngularJS

What is the proper/accepted way to use separate stylesheets for the various views my application uses?

Currently I'm placing a link element in the view/partial's html at the top but I've been told this is bad practice even though all modern browsers support it but I can see why it's frowned upon.

The other possibility is placing the separate stylesheets in my index.html's head but I would like it to only load the stylesheet if its view is being loaded in the name of performance.

Is this bad practice since styling won't take effect until after the css is loaded form the server, leading to a quick flash of unformatted content in a slow browser? I have yet to witness this although I'm testing it locally.

Is there a way to load the CSS through the object passed to Angular's $routeProvider.when ?

Thanks in advance!


I know this question is old now, but after doing a ton of research on various solutions to this problem, I think I may have come up with a better solution.

UPDATE 1: Since posting this answer, I have added all of this code to a simple service that I have posted to GitHub. The repo is located here. Feel free to check it out for more info.

UPDATE 2: This answer is great if all you need is a lightweight solution for pulling in stylesheets for your routes. If you want a more complete solution for managing on-demand stylesheets throughout your application, you may want to checkout Door3's AngularCSS project. It provides much more fine-grained functionality.

In case anyone in the future is interested, here's what I came up with:

1. Create a custom directive for the <head> element:

app.directive('head', ['$rootScope','$compile',
    function($rootScope, $compile){
        return {
            restrict: 'E',
            link: function(scope, elem){
                var html = '<link rel="stylesheet" ng-repeat="(routeCtrl, cssUrl) in routeStyles" ng-href="{{cssUrl}}" />';
                elem.append($compile(html)(scope));
                scope.routeStyles = {};
                $rootScope.$on('$routeChangeStart', function (e, next, current) {
                    if(current && current.$$route && current.$$route.css){
                        if(!angular.isArray(current.$$route.css)){
                            current.$$route.css = [current.$$route.css];
                        }
                        angular.forEach(current.$$route.css, function(sheet){
                            delete scope.routeStyles[sheet];
                        });
                    }
                    if(next && next.$$route && next.$$route.css){
                        if(!angular.isArray(next.$$route.css)){
                            next.$$route.css = [next.$$route.css];
                        }
                        angular.forEach(next.$$route.css, function(sheet){
                            scope.routeStyles[sheet] = sheet;
                        });
                    }
                });
            }
        };
    }
]);

This directive does the following things:

  • It compiles (using $compile ) an html string that creates a set of <link /> tags for every item in the scope.routeStyles object using ng-repeat and ng-href .
  • It appends that compiled set of <link /> elements to the <head> tag.
  • It then uses the $rootScope to listen for '$routeChangeStart' events. For every '$routeChangeStart' event, it grabs the "current" $$route object (the route that the user is about to leave) and removes its partial-specific css file(s) from the <head> tag. It also grabs the "next" $$route object (the route that the user is about to go to) and adds any of its partial-specific css file(s) to the <head> tag.
  • And the ng-repeat part of the compiled <link /> tag handles all of the adding and removing of the page-specific stylesheets based on what gets added to or removed from the scope.routeStyles object.
  • Note: this requires that your ng-app attribute is on the <html> element, not on <body> or anything inside of <html> .

    2. Specify which stylesheets belong to which routes using the $routeProvider :

    app.config(['$routeProvider', function($routeProvider){
        $routeProvider
            .when('/some/route/1', {
                templateUrl: 'partials/partial1.html', 
                controller: 'Partial1Ctrl',
                css: 'css/partial1.css'
            })
            .when('/some/route/2', {
                templateUrl: 'partials/partial2.html',
                controller: 'Partial2Ctrl'
            })
            .when('/some/route/3', {
                templateUrl: 'partials/partial3.html',
                controller: 'Partial3Ctrl',
                css: ['css/partial3_1.css','css/partial3_2.css']
            })
    }]);
    

    This config adds a custom css property to the object that is used to setup each page's route. That object gets passed to each '$routeChangeStart' event as .$$route . So when listening to the '$routeChangeStart' event, we can grab the css property that we specified and append/remove those <link /> tags as needed. Note that specifying a css property on the route is completely optional, as it was omitted from the '/some/route/2' example. If the route doesn't have a css property, the <head> directive will simply do nothing for that route. Note also that you can even have multiple page-specific stylesheets per route, as in the '/some/route/3' example above, where the css property is an array of relative paths to the stylesheets needed for that route.

    3. You're done Those two things setup everything that was needed and it does it, in my opinion, with the cleanest code possible.

    Hope that helps someone else who might be struggling with this issue as much as I was.


    @tennisgent's solution is great. However, I think is a little limited.

    Modularity and Encapsulation in Angular goes beyond routes. Based on the way the web is moving towards component-based development, it is important to apply this in directives as well.

    As you already know, in Angular we can include templates (structure) and controllers (behavior) in pages and components. AngularCSS enables the last missing piece: attaching stylesheets (presentation).

    For a full solution I suggest using AngularCSS.

  • Supports Angular's ngRoute, UI Router, directives, controllers and services.
  • Doesn't required to have ng-app in the <html> tag. This is important when you have multiple apps running on the same page
  • You can customize where the stylesheets are injected: head, body, custom selector, etc...
  • Supports preloading, persisting and cache busting
  • Supports media queries and optimizes page load via matchMedia API
  • https://github.com/door3/angular-css

    Here are some examples:

    Routes

      $routeProvider
        .when('/page1', {
          templateUrl: 'page1/page1.html',
          controller: 'page1Ctrl',
          /* Now you can bind css to routes */
          css: 'page1/page1.css'
        })
        .when('/page2', {
          templateUrl: 'page2/page2.html',
          controller: 'page2Ctrl',
          /* You can also enable features like bust cache, persist and preload */
          css: {
            href: 'page2/page2.css',
            bustCache: true
          }
        })
        .when('/page3', {
          templateUrl: 'page3/page3.html',
          controller: 'page3Ctrl',
          /* This is how you can include multiple stylesheets */
          css: ['page3/page3.css','page3/page3-2.css']
        })
        .when('/page4', {
          templateUrl: 'page4/page4.html',
          controller: 'page4Ctrl',
          css: [
            {
              href: 'page4/page4.css',
              persist: true
            }, {
              href: 'page4/page4.mobile.css',
              /* Media Query support via window.matchMedia API
               * This will only add the stylesheet if the breakpoint matches */
              media: 'screen and (max-width : 768px)'
            }, {
              href: 'page4/page4.print.css',
              media: 'print'
            }
          ]
        });
    

    Directives

    myApp.directive('myDirective', function () {
      return {
        restrict: 'E',
        templateUrl: 'my-directive/my-directive.html',
        css: 'my-directive/my-directive.css'
      }
    });
    

    Additionally, you can use the $css service for edge cases:

    myApp.controller('pageCtrl', function ($scope, $css) {
    
      // Binds stylesheet(s) to scope create/destroy events (recommended over add/remove)
      $css.bind({ 
        href: 'my-page/my-page.css'
      }, $scope);
    
      // Simply add stylesheet(s)
      $css.add('my-page/my-page.css');
    
      // Simply remove stylesheet(s)
      $css.remove(['my-page/my-page.css','my-page/my-page2.css']);
    
      // Remove all stylesheets
      $css.removeAll();
    
    });
    

    You can read more about AngularCSS here:

    http://door3.com/insights/introducing-angularcss-css-demand-angularjs


    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

    链接地址: http://www.djcxy.com/p/68986.html

    上一篇: 重新加载页面给AngularJS HTML5模式提供了错误的GET请求

    下一篇: 如何在AngularJS中包含视图/部分特定样式