ocombe / ocLazyLoad

Lazy load modules & components in AngularJS
https://oclazyload.readme.io
MIT License
2.63k stars 510 forks source link

How to dependency injection using ocLazyLoad #353

Closed m98 closed 7 years ago

m98 commented 8 years ago

This question asked on Stackoverflow but no one answered that, I was curious to know the answer, and I posted that here:

I'm using ocLazyLoad and I have some external angular libraries (Like Chart.js and pascalprecht.translate) and I need to lazy load them in some routes, as you know, for the common angular module dependency injection should be like:

var angularApp = angular.module('myApp',
     ['oc.lazyLoad', 'pascalprecht.translate', 'chart.js']);

Now, I just need to lazy loading pascalprecht.translate in one of my controllers and also lazy loading chart.js, in another controller, but I still need to add inject them to myApp module but I don't know how to inject and I do not use $stateProvider

I tried this my controller that I needed chart.js:

//Load here.
//$ocLazyLoad.load('./panel/dist/test.js');
angular.module('myApp', ['chart.js', [
 './panel/dist/static/chart.min.js',
 './panel/dist/static/angular-chart.min.js'
]]);

$ocLazyLoad.load('./panel/dist/static/chart.min.js');
$ocLazyLoad.load('./panel/dist/static/angular-chart.min.js');

But I got this error:

angular-chart.min.js:10Uncaught Error: Chart.js library needs to included, see http://jtblin.github.io/angular-chart.js/

alo commented 8 years ago

Hi! In your module definition you don't have to inject "chart.js"

angular.module('myApp', [ 'ui.router', 'oc.lazyLoad' ]);

If you are using ui.router:

angular.module('myApp').config(
    ['$stateProvider', '$urlRouterProvider',
    function ($stateProvider, $urlRouterProvider) {
      $urlRouterProvider.otherwise('/access/signin');
      $stateProvider
        .state('chart', {
          url: '/chart-view',
          templateUrl: 'path/to/your/view',
          resolve: {
            store: function ($ocLazyLoad) {
              return $ocLazyLoad.load(
                {
                  serie: true,
                  name: "chart.js",
                  files: [
                    "path/to/Chart.min.js",
                    "path/to/anguar-chart.min.js",
                  ]
                }
              );
            }
          }
        });
      }
    ]
  );
m98 commented 7 years ago

Thanks 👍

very useful, I also added an answer on Stackoverflow for users who are not using ui-router (of course not very different)

alo commented 7 years ago

cool! so you can close the issue!

ignivaravinderrikhi commented 7 years ago

It actually works .... Hey can you explain me how it is injecting dependency ... TIA ...