2015-04-07 195 views
0

我有一個項目,有一個非常快速的開發週期,導致主app.js文件的許多變化。該文件具有用於作爲項目一部分的AngularJS應用程序的配置和控制器。這創造了我試着解決緩存問題如下:動態添加AngularJS腳本

<script type="text/javascript"> 
    var s = document.createElement('script') 
    s.setAttribute('src', 'assets/js/app-v2.js?v='+(new Date().getMilliseconds())); 
    document.body.appendChild(s); 
</script> 

然而,這給我的角度說法錯誤:

Failed to instantiate module appName due to: 
Error: [$injector:nomod] Module 'appName' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument. 

我的HTML是設置爲

<html ng-app="appName">....</html> 

所以我加載腳本後試圖動態地設置ng-app,但這也不起作用。給我同樣的問題。是否可以在app-v2.js文件加載期間或之後動態添加appName?

+0

是什麼的「緩存問題」的本質是什麼?該文件已更新,但是當你刷新你仍然得到舊版本?如果是這樣,我不明白如何設置'ng-app'動態地幫助 –

+0

@NewDev,出於某種原因,即使在服務器上更新文件,我在調用它時會得到一個304 Not Modified標誌。 – Newtt

+0

好的,但你打算如何解決這個動態'ng-app'? –

回答

0

我在面對同樣的問題時從stackoverflow找到了這個答案。

bootstrap()將爲您調用AngularJS編譯器,就像ng-app一樣。

// Make module Foo and store $controllerProvider in a global 
var controllerProvider = null; 
angular.module('Foo', [], function($controllerProvider) { 
controllerProvider = $controllerProvider; 
}); 
// Bootstrap Foo 
angular.bootstrap($('body'), ['Foo']); 

// .. time passes .. 

// Load javascript file with Ctrl controller 
angular.module('Foo').controller('Ctrl', function($scope, $rootScope) { 
$scope.msg = "It works! rootScope is " + $rootScope.$id + 
    ", should be " + $('body').scope().$id; 
}); 
// Load html file with content that uses Ctrl controller 
$('<div id="ctrl" ng-controller="Ctrl" ng-bind="msg">').appendTo('body'); 

// Register Ctrl controller manually 
// If you can reference the controller function directly, just run: 
// $controllerProvider.register(controllerName, controllerFunction); 
// Note: I haven't found a way to get $controllerProvider at this stage 
// so I keep a reference from when I ran my module config 
    function registerController(moduleName, controllerName) { 
    // Here I cannot get the controller function directly so I 
    // need to loop through the module's _invokeQueue to get it 
    var queue = angular.module(moduleName)._invokeQueue; 
for(var i=0;i<queue.length;i++) { 
    var call = queue[i]; 
    if(call[0] == "$controllerProvider" && 
     call[1] == "register" && 
     call[2][0] == controllerName) { 
     controllerProvider.register(controllerName, call[2][1]); 
    } 
} 
} 
registerController("Foo", "Ctrl"); 
// compile the new element 
$('body').injector().invoke(function($compile, $rootScope) { 
$compile($('#ctrl'))($rootScope); 
$rootScope.$apply(); 
}); 

希望它會幫助你