Lazy Experiment

Ben Nadel had an interesting post recently (as usual) that sparked my curiousity. He showed an experiment he had whipped up that provided for lazily adding controllers and services after Angular had been bootstrapped. This, of course, is not supported directly by Angular so his experiment involved duck-punching the module instance and overriding its basic convenience functions.

I thought that was pretty cool but wondered if I could just create a lazy factory.

On this site, each nugget is a view which loads asynchronously when it is selected or navigated to. In this view, I have some markup as shown below:

<div id="lazyTest">
    {{ }} is {{ model.description }}.

It is rendered here:

{{ }} is {{ model.description }}.

This view also contains the following embedded script which executes long after angular has been bootstrapped:

(function() {
"use strict";

// grab the Lazy factory
var Lazy = angular.element(document).injector().get('Lazy');

// declare a new factory that will be used by our lazy controller
// (using a factory just to demostrate that injection works properly)
Lazy.factory('MyLazyData', function() {
    return {
        name: 'Lazy data',
        description: 'very lazy'

// declare a new controller passing element id as the first arg
Lazy.controller('lazyTest', function($scope, MyLazyData) {
    $scope.model = MyLazyData;


The implementation of the Lazy factory can be seen in lazy.js.

There is a reason that angular doesn't provide this functionality out of the box. Lazy services that depend on other lazy services will quickly put you in a bind. But it's fun to experiment.
Note that this view depends on jQuery because it contains embedded script. Angular does not execute embedded script. More info about that in this Stack Overflow thread.