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

前端之家收集整理的这篇文章主要介绍了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)

原文链接:https://www.f2er.com/css/217664.html

猜你在找的CSS相关文章