Oscar Reyes
Oscar Reyes

Reputation: 4342

How to load AngularJS controller file on content loaded

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?

Upvotes: 1

Views: 165

Answers (1)

Jim Buck
Jim Buck

Reputation: 2444

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.

Upvotes: 1

Related Questions