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

我想仅在用户访问我的AngularJS应用程序/站点上的contact.html视图时才加载特定的CSS文件.我找到了这个对我来说几乎有意义的答案 How to include view/partial specific styling in AngularJS charlietfl接受的答案是:

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

06000

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

问题是我不知道在我的$routeProvider中添加代码的确切位置. charlietfl提到将其放在评论中的位置

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

我按照建议修改了我的$routeProvider.我在以下对象中添加了一个解析.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',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: '/'
      });
  });

这会有用吗?

解决方法

我为它做了一个服务.

代码的重要部分:

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)

相关文章

Css常用的排序方式权重分配 排序方式: 1、按类型&#160;...
原文:https://www.cnblogs.com/wenruo/p/9732704.html 先上...
css属性:word-wrap:break-word; 与 word-break:break-all 的...
https://destiny001.gitee.io/color/
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML...
css之background的cover和contain的缩放背景图 对于这两个属...