动态添加AngularJS脚本



我有一个项目的开发周期非常快,这会导致主app.js文件发生许多更改。该文件包含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?

当我面临同样的问题时,我从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();
});

希望它能帮助你

最新更新