动态添加AngularJS脚本

时间:2015-04-07 06:21:24

标签: javascript 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?

1 个答案:

答案 0 :(得分: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();
});

希望它能帮到你