2016-06-19 42 views
0

我是Angular的新手,如果ngRoute等於某些東西,我想知道是否有任何方法來渲染腳本(CSS/JS)。例如,我有以下定義的路由:在AngularJS中有條件地渲染腳本,使用路由

 .when('/', { 
      templateUrl : 'views/index.html', 
      controller : 'ProductsController' 
     }) 
     // route for the contactus page 
     .when('/admin', { 
      templateUrl : 'admin/index.html', 
      controller : 'AdminController', 

     }) 

,我想呈現<link href="css/app.css" rel="stylesheet">在頭上時,路線是"/"<link href="css/admin.css" rel="stylesheet">當路由"/admin"

+0

沒有,這是不支持的選項。 – Claies

+0

嘗試使用required.js。它以AMD模式加載js和CSS。非常適合異步加載js和CSS,延遲加載或按需加載,依賴管理等。 –

+0

您可以使用[this library](https://github.com/GabrielDelepine/angular-css-injector)之類的東西,它提供了編輯頁面中包含的樣式表的服務,並讓您的控制器根據上下文管理這些文件。 –

回答

0

我剛剛找到解決方案,不知道它是否正確,因爲它在</head>之後呈現樣式表,但是這解決了我的問題。我所做的是,我定義了一個MainController爲:

myApp.controller('MainController', ['$scope','$location', '$routeParams', function($scope, $location, $routeParams) { 
    if($location.path() == '/admin') { 
     $scope.isAdmin = true; 
    } 
    else { 
     $scope.isAdmin = false; 
    } 

    }]); 

,而不是將樣式表內</head>在那之後,我剛放置與MainController一個指令和包裝樣式在它的頭後:

<div ng-controller="MainController"> 

    <link href="css/app.css" rel="stylesheet" ng-if="!isAdmin"> 

</div> 
0

<head>你可以把:

<link rel="stylesheet" ng-href={{selectedType}}> 

在主控制器,你可以把條件如果isAdmin

$rootScope.selectedType = isAdmin ? "css/admin.css" : "css/app.css" 

只要確保ng-app是在你的HTML:<html ng-app="myApp">