2015-04-07 148 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(); 
}); 

希望它会帮助你