title: AngularJS Dynamic loading a controller
body: <p>I read a lot about lazzy loading, but I am facing a problem when using $routeProvider.</p>
  
  <p>My goal is to load a javascript file which contains a controller and add a route to this controller which has been loaded previously.</p>
  
  <p><strong>Content of my javascript file to load</strong></p>
  
  <pre><code>angular.module('demoApp.modules').controller('MouseTestCtrlA', ['$scope', function ($scope) {
      console.log("MouseTestCtrlA");
      $scope.name = "MouseTestCtrlA";
  }]);
  </code></pre>
  
  <p>This file is not included when angular bootstap is called. It means, I have to load the file and create a route to this controller.</p>
  
  <p>First, I started writing a resolve function which has to load the Javascript file. But declaring my controller parameter in route declaration gave me an error :</p>
  
  <blockquote>
    <p>'MouseTestCtrlA' is not a function, got undefined</p>
  </blockquote>
  
  <p>Here is the call I am trying to set :</p>
  
  <pre><code>demoApp.routeProvider.when(module.action, {templateUrl: module.template, controller: module.controller, resolve : {deps: function() /*load JS file*/} });
  </code></pre>
  
  <p>From what I read, the controller parameter should be a registered controller </p>
  
  <blockquote>
    <p>controller – {(string|function()=} – Controller fn that should be associated with newly created scope or the name of a registered controller if passed as a string.</p>
  </blockquote>
  
  <p>So I write a factory which should be able to load my file and then (promise style!) I whould try to declare a new route.</p>
  
  <p>It gave me something like below where dependencies is an array of javascript files' paths to load :</p>
  
  <p><strong>Usage</strong></p>
  
  <pre><code>ScriptLoader.load(module.dependencies).then(function () {
      demoApp.routeProvider.when(module.action, {templateUrl: 'my-template', controller: module.controller});
  });
  </code></pre>
  
  <p><strong>Script loader</strong> </p>
  
  <pre><code>angular.module('demoApp.services').factory('ScriptLoader', ['$q', '$rootScope', function ($q, $rootScope) {
          return {
              load: function (dependencies)
              {
                  var deferred = $q.defer();
                  require(dependencies, function () {
                      $rootScope.$apply(function () {
                          deferred.resolve();
                      });
                  });
                  return deferred.promise;
              }
          }
      }]);
  </code></pre>
  
  <p><strong>Problem</strong></p>
  
  <p>I still have this javascript error "'MouseTestCtrlA' is not a function, got undefined" which means Angular could not resolved 'MouseTestCtrlA' as a registered controller. </p>
  
  <p>Can anyone help me on this point please ?</p>