title: AngularJS: lazy loading controllers and content
body: <p>In this simplified scenario, I have two files: index.htm, lazy.htm.</p>
  
  <p>index.htm:</p>
  
  <pre><code>var myApp = angular.module('myApp', []);
  myApp.controller('embed',function($scope){
      $scope.embed = 'Embedded Controller';
  });                  
  &lt;div ng-controller="embed"&gt;{{embed}}&lt;/div&gt;    
  &lt;div ng-include="'lazy.htm'"&gt;&lt;/div&gt;
  </code></pre>
  
  <p>lazy.htm</p>
  
  <pre><code>myApp.controller('lazy',function($scope){
      $scope.lazy = 'Lazy Controller';
  });
  &lt;div ng-controller="lazy"&gt;
      {{lazy}}
  &lt;/div&gt;
  </code></pre>
  
  <p>The result is an error: "Argument 'lazy' is not a function, got undefined"</p>
  
  <p>Using a function instead</p>
  
  <p>lazy.htm</p>
  
  <pre><code>function lazy($scope) {
      $scope.lazy = 'Lazy Controller';
  }
  &lt;div ng-controller="lazy"&gt;
      {{lazy}}
  &lt;/div&gt;
  </code></pre>
  
  <p>This works until version 1.3 beta 14. In beta 15 was removed the global controller functions: <a href="https://github.com/angular/angular.js/issues/8296" rel="noreferrer">https://github.com/angular/angular.js/issues/8296</a></p>
  
  <p>So now, what is the better way to get angularized contents of lazy.htm dynamically?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>In this article (<a href="http://ify.io/lazy-loading-in-angularjs" rel="noreferrer">http://ify.io/lazy-loading-in-angularjs</a>) I found another possible solution. The $controllerProvider allow us to register new controllers after angular bootstrap. Works like a charm. Tested in <strong>v1.3.0-beta.18</strong></p>
  
  <p>index.htm:</p>
  
  <pre><code>var myApp = angular.module('myApp', [])
  .controller('embed',function($scope){
      $scope.embed = 'Embedded Controller';
  })
  .config(function($controllerProvider) {
      myApp.cp = $controllerProvider;
  });
  
  &lt;div ng-controller="embed"&gt;{{embed}}&lt;/div&gt;    
  &lt;div ng-include="'lazy.htm'"&gt;&lt;/div&gt;
  </code></pre>
  
  <p>lazy.htm</p>
  
  <pre><code>myApp.cp.register('lazy',function($scope){
      $scope.lazy = 'Lazy Controller';
  });
  &lt;div ng-controller="lazy"&gt;
      {{lazy}}
  &lt;/div&gt;
  </code></pre>
  
  <p><strong>UPDATE 2:</strong></p>
  
  <p>Two other alternatives that works are:</p>
  
  <p>lazy.htm</p>
  
  <pre><code>_app = $('[ng-app]').scope();    
  _app.lazy = function($scope) {
      $scope.lazy = 'Lazy Controller';
  };
  </code></pre>
  
  <p>OR</p>
  
  <pre><code>var $rootScope = $('[ng-app]').injector().get('$rootScope');        
  $rootScope.lazy = function($scope) {
      $scope.lazy = 'Lazy Controller';
  }; 
  </code></pre>
  
  <p>But I believe these last two examples should not be used in production.</p>