如何在AngularJS $ routeProvider中附加样式表?

时间:2013-08-28 14:32:54

标签: css angularjs conditional route-provider

我只想在用户访问AngularJS应用/网站上的contact.html视图时加载特定的CSS文件。我发现这个答案几乎对我有用How to include view/partial specific styling in AngularJS charlietfl接受的答案是:

  

可以在$routeProvider内追加新的样式表。对于   简单我使用字符串,但也可以创建新的链接元素,   或为样式表创建服务

/* 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">');
}
     

页面中预先编码的最大好处是任何背景图像都会   已经存在,FOUC

的谎言较少

问题是我不知道$routeProvider中添加代码的具体位置。 charlietfl提到将其放在注释中的位置

  

如果没有调用路线的时间,则不会。可以把这段代码放进去   控制器回调在routeProvider中,或者也许   在解决回调中可能会更快触发

我已根据建议修改了$routeProvider。我在resolve后面的对象中添加了.when('/contact'。这是我的代码

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: '/'
      });
  });

这会有用吗?

4 个答案:

答案 0 :(得分:8)

我为它做了一个服务。

代码的重要部分:

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"});

Github中的完整代码:https://github.com/Yappli/angular-css-injector

答案 1 :(得分:2)

更新Here is the solution to inject(load) a specific CSS using the $routeProvider

下面介绍的解决方案是根据可在其他情况下使用的路线应用不同类别和页面标题的替代方法。

对于每条路线,我创建了一个名为“ bodyClass ”和“标题”的新密钥(但您可以调用任何您喜欢的密码),它看起来像这样:

'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'
    });
});

然后,对于每个$ routeChangeSuccess事件,我更改页面的<title>以及<body>的类。

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;
      }
    });
}]);

您将上面的代码放在相同的主 app.js (例如)文件中。

在我的index.html页面上,它提供了视图,我有以下代码来获取标题和类:

<title>{{ title }}</title>

<body class="{{ bodyClass }}">

因此,如果我访问我的应用程序的主页,标题标记将是

<tittle> Home - My Cool App</tittle>

并且正文标记将是

<body class="home">

它的工作就像一个魅力。

我知道此解决方案不会加载CSS文件,但您可以将这些样式放在 .contact '类中,只有当您点击时才会应用具体路线。

不确定是否能解决您的问题,但我希望这有助于或至少指出您正确的方向。

答案 2 :(得分:2)

对于完整的解决方案,我建议使用AngularCSS

正如您所知,在Angular中,我们可以在页面和组件中包含模板(结构)和控制器(行为)。 AngularCSS支持最后一个缺失的部分:附加样式表(演示文稿)。

路线示例:

$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'
    }
  ]
});

指令示例:

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

您可以阅读有关AngularCSS here的更多信息:

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

答案 3 :(得分:0)

我认为最好/最简单的答案是我离开的here。有人问了同样的问题,所以我想出了一些简单的代码和一个小的github仓库来处理这个场景。

相关问题