With your router

$ocLazyLoad works well with routers and especially ui-router. Since it returns a promise, use the resolve property to make sure that your components are loaded before the view is resolved:

$stateProvider.state('index', {
    url: "/", // root route
    views: {
        "lazyLoadView": {
            controller: 'AppCtrl', // This view will use AppCtrl loaded below in the resolve
            templateUrl: 'partials/main.html'
        }
    },
    resolve: { // Any property in resolve should return a promise and is executed before the view is loaded
        loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
            // you can lazy load files for an existing module
             return $ocLazyLoad.load('js/AppCtrl.js');
        }]
    }
});

If you have nested views, make sure to include the resolve from the parent to load your components in the right order:

$stateProvider.state('parent', {
    url: "/",
    resolve: {
        loadMyService: ['$ocLazyLoad', function($ocLazyLoad) {
             return $ocLazyLoad.load('js/ServiceTest.js');
        }]
    }
})
.state('parent.child', {
    resolve: {
        test: ['loadMyService', '$ServiceTest', function(loadMyService, $ServiceTest) {
            // you can use your service
            $ServiceTest.doSomething();
        }]
    }
});

It also works for sibling resolves:

$stateProvider.state('index', {
    url: "/",
    resolve: {
        loadMyService: ['$ocLazyLoad', function($ocLazyLoad) {
             return $ocLazyLoad.load('js/ServiceTest.js');
        }],
        test: ['loadMyService', '$serviceTest', function(loadMyService, $serviceTest) {
            // you can use your service
            $serviceTest.doSomething();
        }]
    }
});

Of course, if you want to use the loaded files immediately, you don't need to define two resolves, you can also use the injector (it works anywhere, not just in the router):

$stateProvider.state('index', {
  url: "/",
  resolve: {
    loadMyService: ['$ocLazyLoad', '$injector', function($ocLazyLoad, $injector) {
      return $ocLazyLoad.load('js/ServiceTest.js').then(function() {
        var $serviceTest = $injector.get("$serviceTest");
        $serviceTest.doSomething();
      });
    }]
  }
});

Did this page help you?