2014-09-04 67 views
0

我有一個應用程序,其中包含許多視圖,這些視圖各不相同,而且數量足以證明根據當時哪個視圖處於活動狀態動態加載CSS文件。這是否適合使用AngularJS服務?

我研究了用角度動態「加載」CSS文件的各種方法,甚至發現了一個可以工作的插件,儘管它在實現時有點笨拙。

我做了一些關於原生JS方法的研究來做到這一點,並決定以更有角度的方式實現它。我將下面的服務注入路由控制器。

我的實現方法(使用服務)是否正確?如果不是,這種邏輯的正確場所是什麼?

HTML:

<head> 
... 
    <link id="library-css" href="~/Styles/libraryCSS" rel="stylesheet" type="text/css" disabled /> 
    <link id="results-css" href="~/Styles/resultsCSS" rel="stylesheet" type="text/css" disabled /> 
... 
</head> 

的AngularJS服務:

myServices.service("CSSLoader", [function() { 

    var cssLinks = {}, 
     linkToActivate = {}; 

    (function init() { 
     //loading the <link> elements into the cssLinks object for later retrieval 
     cssLinks = { 
      library: document.getElementById("library-css"), 
      results: document.getElementById("results-css") 
     }; 
    })(); 

    this.loadCSS = function (cssReference, retainPreviouslyLoadedCSS) { 
     if (!cssReference) { throw "CSS Link must be provided.";} 

     if (!retainPreviouslyLoadedCSS) { 
      //first disables any links that are active 
      for (var cnt in cssLinks) { 
       cssLinks[cnt].disabled = true; 
      } 
     } 

     linkToActivate = cssLinks[cssReference]; 
     if (!linkToActivate) { throw "CSS Link, (" + cssReference + "), that was provided cannot be found."; } 

     linkToActivate.disabled = false; 
    }; 

}]); 

謝謝!

回答

1

請發現我爲您創造的plunker。 它基於一個指令,該指令監視與其自己的id相對應的範圍變量。

app.directive('disablecss', function() { 
    return { 
    link: function(scope, element, attrs) { 
     scope.$watch('cssToSet.'+attrs.id, function(value,oldvalue) { 

其中attrs.id對應於其中指令被設爲

<link href="resultCSS.css" id="resultCSS" rel="stylesheet" disablecss /> 
    <link href="libraryCSS.css" id="libraryCSS" rel="stylesheet" disablecss /> 

scope屬性automaticaly由關聯到局部視圖控制器修改的鏈路ID

app.config(function($routeProvider) { 
    $routeProvider. 
    when('/view1', { 
     controller:'View1Ctrl', 
     templateUrl:'partial1.html' 
    }). 
    when('/view2', { 
     controller:'View2Ctrl', 
     templateUrl:'partial2.html' 
    }). 
    otherwise({redirectTo:'/'}); 
}); 


app.controller('View1Ctrl',['$scope',function($scope,$rootscope){ 
    $scope.cssToSet.resultCSS=true; 
    $scope.cssToSet.libraryCSS=false; 
}]); 

idem for View2Ctrl 

不要猶豫,如果有什麼不清楚.BB

+0

我喜歡這個解決方案,它是_even more_ angular!謝謝 – tedwards947 2014-09-05 14:11:10