user2638841 user2638841 - 15 days ago 5
AngularJS Question

Difference between app.register.controller and app.controller in AngularJS

I don't know when to use app.register.controller and app.controller to create controller after module is created. I have googled but I didn't find clear difference between two scenarios. please post sample example.

Answer

Simple Answer

You can use app.controller to register providers before the app starts (i.e., before boostrap or ng-app, just for build). And app.register.controller is used to register a new provider when the app has already started.

A More Elaborated Examplanation

AngularJs loads all the providers registered before the module bootstrap, once your module gets bootstraped, angular won't look for registered providers anymore. It's ok for most apps but in some cases, you will have to load new providers at run time (i.e., after the app gets bootstraped), therefore, you will have too register it manually.

For example:

var app = angular.module('myApp', []);

app.controller('myController1', function (){});

angular.element(documento).ready(function () {
    // equivalent to ng-app attribute
    angular.bootstrap(document, ['myApp']);
});

At this point, angular will load all providers registered before the bootstraping. However, if you try to register a controller again, it won't get loaded on your application, because angular loads it just when bootstrap.

So, to register a provider at run time, you have to expose the angulars providers factory on your module like so:

app.config(function($controllerProvider, $compileProvider, $filterProvider, $provide) {
    app.register = {
        controller: $controllerProvider.register,
        directive: $compileProvider.directive,
        filter: $filterProvider.register,
        factory: $provide.factory,
        service: $provide.service
    };
});

Check this answer for more info: http://stackoverflow.com/a/20922872/4488121

Finally, now it allow you to register a provider afer the app bootstrap (i.e., at run time).

app.register.controller('myController2', function (){});

This approach is mostly used for lazy loading providers.