1

I'm new to Angular.JS and i'm trying to load a controller file dinamically when a content loaded from ng-include is requesting it, i do this way because the page i'm building will have multiple controllers and i rather make the initial page to load fast due to it's size, i am not sure to do this and i thought i would achieve it by just doing:

<script type="text/javascript" src="js/controllers/controllerFile.js"></script>

inside the content loaded.

the controller File is like this

app.controller('parseQuery', function()
{
    this.object = 'Enter query and parse.';

    this.parse = function()
    {
        this.object = JSON.stringify(window.getParam(this.query), null, '\t');
    };

    this.getURL = function()
    {
        this.query = document.URL;
        this.parse();
    };
});

the html file calls the controller with ng-controller as it should work. But when the content is loaded, javascript returns an error Argument 'parseQuery' is not a, so nothing works, how can i achieve to load a controller file after application is already bootstraped?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Oscar Reyes
  • 4,223
  • 8
  • 41
  • 75
  • 2
    Angular cannot lazy load controllers (or services, or anything else angular) after having been bootstrapped. Out of the box anyway. You could take a look at https://github.com/ocombe/ocLazyLoad or wait for Angular 2 which will support lazy loading. – jlowcs Mar 13 '15 at 19:11
  • @jlowcs So i have no choice but to load all controllers in the initial page? – Oscar Reyes Mar 13 '15 at 19:14
  • i am quite sure your total code size is much less then angular.js itself, which must be loaded for sure - so whats the point? – Petr Averyanov Mar 13 '15 at 19:18
  • @nosthertus yes. Although, especially if minified and gzipped, your code shouldn't be very heavy. Lazy loading is usually necessary mostly for large apps. – jlowcs Mar 13 '15 at 19:27
  • possible duplicate of [AngularJS: Loading a controller dynamically](http://stackoverflow.com/questions/15250644/angularjs-loading-a-controller-dynamically) – isherwood Mar 13 '15 at 19:30

1 Answers1

1

To lazy load your scripts, you'll want to check out an AMD or CommonJS loader. These libraries provide the ability to load scripts on demand.

Dan Wahlin has an excellent blog post detailing how to use RequireJS with angular.

In the 1.3.14 AngularJS recieved support for CommonJS. That will be your best bet.

Jim Buck
  • 2,383
  • 23
  • 42