bajky
bajky

Reputation: 342

Loading components and other dependencies with ocLazyLoad plugin

I'm working with AngularJS and ocLazyLoad plugin. And I can't find a solution for my problem.

I have created one component (named as component.js) and controller for this component (in separate file componentCtrl.js) and then I have constants, which I use in controller(it's too in separated file constants.js). And I need to load these files. When I use something like this:

loadPlugin: function ($ocLazyLoad) {
                    return $ocLazyLoad.load(
                        {
                            files: ['../componentCtrl.js','../constants.js',../,'component.js']
                        },...

My dependencies is loaded fine. But I need this component in more views. Then I have to write this code again and again. Can I define this array of resources before using in lazy load function?

When I have module, It's simple

$ocLazyLoadProvider.config({
  modules: [{
    name: 'TestModule',
    files: ['source1', 'source2',..., 'sourceN']
  }]
});

But I don't have special module for this component.It's possible with this plugin ?

Upvotes: 1

Views: 756

Answers (1)

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

You can define some constant or global variable and add your all component files there like this:

angular.module('app')
        .constant('SIMPLE_COMPONENTS', {
            comp1: ['../componentCtrl.js', '../constants.js', 'component.js'],
            comp2: ['../componentCtrl2.js', '../constants2.js', 'component2.js'],
            compfoo: ['../componentfoo.js', '../constantsbar.js', 'componentfoo.js']
        });

Then define a function inside your state configuration like:

function getMeFoo(src) {
    return ['$ocLazyLoad', 'SIMPLE_COMPONENTS', function ($ocLazyLoad, SIMPLE_COMPONENTS) {
        if (SIMPLE_COMPONENTS[src]) {
            return $ocLazyLoad.load(SIMPLE_COMPONENTS[src]);
        }
    }]
}

Now simply use them in your state configuration:

.state('app.foo', {
    url: '/foo',
    templateUrl: 'views/foo.html',
    resolve: {
        dep1: getMeFoo('comp1')
    }
})

.state('app.bar', {
    url: '/bar',
    templateUrl: 'views/bar.html',
    resolve: {
        dep1: getMeFoo('comp1'),
        dep2: getMeFoo('comp2')
    }
});

Upvotes: 1

Related Questions