Giter Club home page Giter Club logo

oclazyload's Introduction

Lazy load modules & components in AngularJS


Find all the documentation (and more) on https://oclazyload.readme.io

ocLazyLoad

----

Key features

  • Dependencies are automatically loaded
  • Debugger friendly (no eval code)
  • The ability to mix normal boot and load on demand
  • Load via the service or the directive
  • Use the embedded async loader or use your own (requireJS, ...)
  • Load js (angular or not) / css / templates files
  • Compatible with AngularJS 1.2.x/1.3.x/1.4.x/1.5.x/1.6.x

Looking for help

I'm looking for contributors to help me maintain the code (I'm gonna switch to Angular 2 soon, and I won't be much more invested in Angular 1 & ocLazyLoad). If you're interested, send me a tweet @OCombe or an email: [email protected] !

oclazyload's People

Contributors

alexan avatar alonl avatar booleanbetrayal avatar circlingthesun avatar danthareja avatar datanotion avatar gbirman-iseatz avatar hupfis avatar johnlindquist avatar jvmccarthy avatar kination avatar kwangin avatar lookfirst avatar martinratinaud avatar msak avatar ocombe avatar olegskl avatar phenomnomnominal avatar renzocastro avatar sjoerd222888 avatar takeshi avatar taz avatar vnica avatar websirnik avatar xcid avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

oclazyload's Issues

Lazy loading custom directives were not invoked/compiled

I wrote couple test programs using your ng module and works great except directives. I have lazy loaded a module which provides some utilities in the form of angular directives which are never invoked. Any pointers for where I should look into. This would make utilizing your solution to the fullest.

Directive Source Code Follows:

    angular
        .module(
            'gridModule', 
            [
                'ngGrid'
            ]
        )
        .directive(
            'persons',
            [   
                '$scope',
                function( $scope ) {
                    return {
                        restrict    : 'AE',
                        replace     : true,
                        templateUrl : 'components/grid/partials/grid.html',
                        //template  : '<div><span>{{test}}</span><br/><div ng-grid="gridOptions" class="gridStyle"></div></div>',
                        compile     : function() {
                            console.info("From <persons> directive compile()...");
                            return {
                                pre : function preLink() { 
                                    console.info("Prelink");                        
                                },
                                post: function postLink( $scope, iElement, iAttrs, controller ) {
                                    console.info("Postlink");
                                }
                            };
                        },
                        controller  : function( $scope ){
                            console.info( "From <persons> directive controller()..." );
                            $scope.test     = "Hey again";

                            $scope.myData   = [
                                {
                                    name: "Moroni", 
                                    age : 50
                                },
                                {
                                    name: "Tiancum", 
                                    age : 43
                                },
                                {
                                    name: "Jacob", 
                                    age : 27
                                },
                                {
                                    name: "Nephi", 
                                    age : 29
                                },
                                {
                                    name: "Enos", 
                                    age : 34
                                }
                            ];

                            $scope.gridOptions  = { 
                                data: 'myData' 
                            };
                        }
                    };
                }
            ]
        );

Any clever idea how to use lazy loaded module parts in sibling resolves?

Let us have e.g. this state:

       ...
      .state('app.detail', {
        url: '/detail/:id',
        templateUrl: 'js/modules/detail/detail.tpl.html',
        controller: 'Detail',
        resolve: {
          // this loads Detail module containing DetailFactory service
          module: function ($ocLazyLoad) {
            return $ocLazyLoad.load({
              name: 'app-seed.detail',
              files: ['modules/detail/detail.module']
            });
          },
          // this fails miserably
          detail: function (DetailFactory) {
            return DetailFactory.get();
          }
        }
        ...

I would really love to use lazy loading of module and immediately use it's parts in another resolves. I was e.g. trying to force-reload state again after resolving the $ocLazyLoad.load() but that didn't help. Transition to new state dies immedietely with calling detail resolve (which should inject data model into my controller).

Does anybody battled this problem too or anyone has some clever solution to this?

ocLazyLoad loads my directives twice

Hi dear ocombe.
thanks a lot for your framework.
I have a problem with your framework when I then js files is loading in $routeProvider.
I have added my js files directives into index.html. and load the services and controllers using your framework. directives and controllers and services are defined in 'application' module. when I load js files using $ocLazyLoad, your framework runs the directive twice and I see this error:
Multiple directives [uiInputText, uiInputText] asking for template on: ......

run method of angular module

Hello lazy loaders,

i'm playing with JS and lazy loading with angular. Everything was fine until i encouter a little issue. It seems in some case, the run method of an angular module cause an issue. I created an example and uploaded it : https://github.com/bidiboom/lazyloadtest

i have the issue with the shell view of the given example (#!/shell). The view has a dependency to ng grid and ng grid seems to have a run method. When ocLazyLoad try to launch the run block (line 693, runBlocks), it encouter a kind of NPE (sorry, java background) : Cannot read property 'invoke' of undefined. ocLazyLoad try to resolve the injector at line 46 (getInstanceInjector) and both instanceInjector and $rootElement.data('$injector') are empty.

am i doing something wrong or is the case out of the scope of the lib ?

if you need more info, don't hesitate, thks!

Lazy Loading Routes with angular-ui-router

Perhaps this is a question for the angular-ui-router team, but it seams like a common use case so perhaps it should be better documented.

I am trying to lazy load modules that define additional ui states and routes. Upon successful loading, ui-router does not make ui-sref links (even after a $state.refresh). Here is an example.

http://plnkr.co/edit/L4RA75kylgMtLWzhS2Z0

Clicking on the button fetches the app2 module and add routes (verifiable by $state.get()), but the link does not render an href.

IE 8 incompatibility due to indexOf usage

At the moment lazy load is incompatible with IE8 due to use of indexOf. Could a workaround be added, maybe just a simple implementation of Array.prototype.indexOf?

usage

This is not an issue as such but brain death perhaps :)

$ocLazyLoad.load({
            name: 'Utils',
            files: ['resources/modules/utils.js']

        }).then(function () {
            $scope.module.ready = true;
        });

how do I refer to the service or controller here?

// e.g greeter.getGreet()
(if this isn't clear let me know)

// now all is loaded...this is the utils module
angular.module('Utils', [])
.service('greeter', function () {
this.greet = "Hello From Utils Module";
this.getGreet = function () {
return this.greet;
}
})
.controller('utilCtrl', function (greeter) {
this.greeting = greeter.getGreet();
})

feature request: supporting a global callback called when a module is registered

Hi,
i could see advantages if the provider would support to register a global callback called when a new module is registered.
For example, in a modularized project using angular-translate + i18n files per modules, that callback could load the translation files of the module just loaded.

That callback should be called in the register() function if i'm not wrong (to keep working properly when all js files are merged with r.js;).

Lazy loading with reconfig: true edge cases

I have had fair success using ocLazyLoad with ui-router-extras futureStates to lazy load requirejs-bases angular modules that define ui-router states. Huh! that line included some 4 packages.

I have had to use the reconfig: true so far. Now, I am trying to create a demo app and for some reason, I can never get the config block of the second lazy loaded module to run.

Run with the example and the first lazy loaded module (choose apple, or orange) works.
Example
Source code
ocLazyLoad code

Breakpointing in js/states/apple.js and js/states/orange.js, you will find that whichever one is clicked first gets its config block run properly, while the second lazy loaded module would not.

Any further insights as to what might be happening?

lazy loaded state, refresh page, localhost

Hi,

great job on lazy loading modules, really very useful.
I have on question, I think i followed the examples on ocLazyLoad and ui-router, everything wirks fine,
however I notice one issue, happening only on local, node.js app, on herokuaoo all works fine.
If I go to state that is resolved with ocLazyLoad for the first time all is well, if i refresh page, the controller for the state is not instantiated, this is console error:

Error: [ng:areq] http://errors.angularjs.org/1.2.14/ng/areq?p0=NotesController&p1=not%20aNaNunction%2C%20got%20undefined
at Error (native)
at https://code.angularjs.org/1.2.14/angular.min.js:6:450
at xb (https://code.angularjs.org/1.2.14/angular.min.js:18:360)
at Pa (https://code.angularjs.org/1.2.14/angular.min.js:18:447)
at https://code.angularjs.org/1.2.14/angular.min.js:63:94
at http://angular-ui.github.io/ui-router/release/angular-ui-router.js:2797:28
at A (https://code.angularjs.org/1.2.14/angular.min.js:50:23)
at h (https://code.angularjs.org/1.2.14/angular.min.js:43:83)
at https://code.angularjs.org/1.2.14/angular.min.js:42:255
at updateView (http://angular-ui.github.io/ui-router/release/angular-ui-router.js:2733:23)

Just curious, it might be something with either order of exectution, or cache ?

the app is deployed here, http://ngproject.herokuapp.com/#/main, all sources are unminified, could you please take a look ?
the lazyloaded state is /notes, NotesModule.js.....

Thank you in dvance

Martin

handling browser cache

do you have any suggestion to handle code version for template and javascript without force user to clear cache..

please make example more than one page using ui.router

this code not work if access page directly

    .state('index.blog', {
        url: '/blog/new',
        // templateUrl:'assets/app/partials/blog/writeblog.html',
        views: {
            "indexView": {
                templateUrl: '/partials/page.html'
            },
            "":{
                templateUrl:'assets/app/partials/blog/writeblog.html',                  
            }
        },
        resolve: {
            page: ['$ocLazyLoad', function($ocLazyLoad) {
                return $ocLazyLoad.load({
                    name: 'PageModule',
                    files: ['assets/app/js/modules/pageModule.js']
                });
            }]  
        }});

if I remove resolve, it works well..I don't know how to add oclazyload for make another page, event it doesn't return any error..

please make example for deeper view

detect resource loading

Hi, I need to make loading indicator inside ui-view while changine page and detection if modules or lazy templateurl failed to load or load time too long..
how to handle it?

oc-lazy-load directive does not display template

This could be an issue with usage, but i cannot seem to find a good example.

When I use the directive like this the controller will work, but the directive (my-ee) will not.

<div oc-lazy-load="{name: 'e', files: ['/modules/rcm-js-lib/TEMP/e.js']}">
    <div ng-controller="e">CONTROLLER {{modele}}</div>
    <div data-my-ee>
        DIRECTIVE DEFAULT
        <input type="text" ng-model="modele"><button ng-click="submitE()" />
        Ed: {{modele}}
    </div>
</div>

When I use the directive to try to load a template, it does not appear to work. I have tried multiple formats:

    <div oc-lazy-load="{name: 'e', files: ['/modules/rcm-js-lib/TEMP/e.js'], template: '/modules/rcm-js-lib/TEMP/etemplate.html'}">
        <div ng-include="modules/rcm-js-lib/TEMP/etemplate.html"></div>
    </div>


    <div oc-lazy-load="{name: 'e', files: ['/modules/rcm-js-lib/TEMP/e.js', '/modules/rcm-js-lib/TEMP/etemplate.html'], template: '/modules/rcm-js-lib/TEMP/etemplate.html'}">
    </div>



<div oc-lazy-load="{name: 'e', files: ['/modules/rcm-js-lib/TEMP/e.js'], template: '/modules/rcm-js-lib/TEMP/etemplate.html'}">
</div>

Lazy loading angular-google-maps

Hi,

I'm using ocLazyLoad to load the angular-google-map module (http://angular-google-maps.org/)

With this mecanism, I'm able to lazy load the google maps API only on demand.
Then, I lazy load the google-map module.

The issue is that directive 'googleMap' doesn't seem to execute.

What am I doing wrong in ocLazyLoading configuration?

Thanks.

Non standard use case - multiple angular applications?

Hi,

so i have some sort of non standard setup - multiple angular applications that reuse same modules. For now, the required module files are included into each application in the html files, but i would like to do some kind of automatic file loading based on module.

Would this sort of scenario be possible with ocLazyLoad:

/* automatically generated and included by all applications */
var modules = {
  "module1": {
    "name": "module1",
    "files": [
      "scripts/modules/module1/fileA.js",
      "scripts/modules/module1/fileB.js",
      "scripts/modules/module1/fileC.js",
      "scripts/modules/module1/fileD.js"
    ]
  },
  "module2": {
    "name": "module2",
    "files": [
      "scripts/modules/module2/fileA.js",
      "scripts/modules/module2/fileB.js",
      "scripts/modules/module2/fileC.js",
      "scripts/modules/module2/fileD.js"
    ]
  },
  "module3": {
    "name": "module3",
    "files": [
      "scripts/modules/module3/fileA.js",
      "scripts/modules/module3/fileB.js",
      "scripts/modules/module3/fileC.js",
      "scripts/modules/module3/fileD.js"
    ]
  },
};
/* First application uses module1 and module2, i would like to get them loaded automatically */
angular.module('indexApp', [
  'ngSanitize',
  'ngRoute',
  'oc.lazyLoad',
  modules.module1,
  modules.module3
]);
/* Second application uses module2 only */
angular.module('accountApp', [
  'ngSanitize',
  'ngRoute',
  'oc.lazyLoad',
  modules.module2
]);

The module config is not triggered

It seems that the config part of a module lazy loaded is not triggered:

angular.module('order', []).config(['$stateProvider', function($stateProvider) {
   console.log('in order.config');
   console.log('$stateProvider');
   console.log($stateProvider);
}]);

I should check out if this is actually the case, and if so fix it

example2 mistake

Originally I thought this was a bug in ocLazyLoad, but then I realized that example2 is missing this:

loadedModules: ['main-app-module-name']

It doesn't really make a difference for such a simple example though...

Multiple modules load error

In version 0.2.0 calling this works good:

$ocLazyLoad.load([
  {name: 'module_name1', files: ['path/to/module1.js']},
  {name: 'module_name2', files: ['path/to/module2.js']},
]);

but in latest version throws exception. i use angular.js 1.2.14

Error: [$rootScope:inprog] $digest already in progress

When requireJS loading the files & template, the template loading will throw the above error.

It is caused by "scope.$apply(function() {" in the function "". The $apply will invoke "beginPhase(phase)". When it find the .$$phase isn't null, the above exception will be thrown.

function loadTemplate(url, callback) {

So I believe you need add a check. Whne $$phase isn't null, use "scope.$eval" instead of "scope.$apply"

For example, ocLazyLoad.directive(). The loadTemplate is invoked in the call back of load()

scope.$watch(attr.ocLazyLoad, function(moduleName) {

     $ocLazyLoad.load(moduleName).then(function(moduleConfig) {
            ....
            loadTemplate(moduleConfig.template, function(template) {

Error when using $templateCache in lazy-loaded runBlock

I'm trying to load ngGrid as a lazy-loaded module, which works correctly (using the code in the pullrequest I've also sent) for the most part.
Unfortunately, when executing the runBlocks I run into this error:

[$injector:unpr] Unknown provider: $templateCache

Now, the $injector we're using is obviously the instance injector from the main app module (since its initialized once for the ocLazyLoad service).
So, I thought I'd retrieve the injector like this:

angular.injector([moduleName, 'ng']);

Only that call leads to similar errors.

When I use this:

angular.injector(['ng']);

The registration works correctly, and the run block is executed without error.
Only once ngGrid is being used I run into errors when the code is trying to retrieve a template.

So, my deduction is that each angular module has its own instance of the $templateCache and the trick is now to use the correct $injector to execute the runBlocks in order to make sure that the correct $templateCache is passed in.

The only question that remains is HOW, I'm hoping someone can help me out here because I think I've hit a wall...

thanks in advance.

Add tests

If anyone wants to help me, this lib could really use some unit and e2e tests !

sometimes error occured

I made this code
files: [
'http://maps.google.com/maps/api/js?v=3.2&sensor=false',
'/assets/bower_components/leaflet-dist/leaflet.js',
'/assets/bower_components/leaflet-plugins/layer/tile/Google.js',
'/assets/bower_components/angular-leaflet-directive/dist/angular-leaflet-directive.min.js',
'/assets/app/modules/map/monevModule.js'
]

sometimes got ReferenceError: L is not defined

if I put dependencies in html page, it always work..
I mean maybe second module not wait first library

Dependency injection on the topmost module

Hi,

I need help understanding why dependency injection wouldn't work, if i try to use ocLazyLoad on the topmost module. Like so:

var demoApp = angular.module('demoApp', ['ngAnimate', 'oc.lazyLoad', {
     name: 'subModule',
     files: ['js/subModule.js']
}]);

Is there something I missed, or is this use not intended?

lazyload via ng-include does not load the controller in time

I have a ng-include tag where I am including an html template. In that template, I use the oc-lazy-load attribute directive to load the module that contains the controller that is referenced in the template. I get the error that the controller is undefined. Should this work?

<ng-include src="/rdf.service/views/graph/view.html"></ng-include>

The view.html looks like:

<div oc-lazy-load="{ name: 'graph', files: ['/rdf.service/views/graph/view.js'] }" ]
  ng-controller="GraphController">
    <table>
        <tr>
            <th>Key</th>
            <th>Value</th>
        </tr>
        <tr ng-repeat="(key,values) in resource">
            <td>{{key}}</td>
            <td><div ng-repeat="value in values" ng-bind-html="renderRdfValue(value)"></div></td>
        </tr>
    </table>
</div>

Looking at the network trace, I can see that the view.js does not get fetched before the error is thrown. If I removed the ng-controller tag, then I can see the view.js being fetched. But of course, it does not work in that case.

Thanks,

-tj

Bug: Inline Array Annotation does not work in lazy loaded module configs

My head almost exploded till I found what is causing routing errors in my app... :)

The problem:
When you use Inline Array Annotation in your lazy loaded config, the config (except the first one) seems to be left unexecuted.. e.g.:

angular.module('foo', [])    
  .config(['$stateProvider', function ($stateProvider) {
    $stateProvider
      .state('foo', { // not working!
        url: '/foo/:fooId?foo1&foo2',
        template: '<div></div>'
      });
  }]);

But this works and the route foo gets added into app (I am using FutureStates btw):

angular.module('foo', [])    
  .config(function ($stateProvider) {
    $stateProvider
      .state('foo', {
        url: '/foo/:fooId?foo1&foo2',
        template: '<div></div>'
      });
  });

Using $inject Property Annotation is OK too. Worth noting is that a first lazy loaded config gets executed, but after that every other fails. Sure I use reconfig: true.

This is one nasty bug.

Load files in serie

EDIT: this is just a discussion about possible syntaxes, not the real implementation

The current native loaders will download all the files from a module in parallel.
For example, with the following setup:

$ocLazyLoad.load([{
    name: 'TestModule',
    files: [
        'testModule.js',
        'testModuleCtrl.js',
        'testModuleService.js'
    ]
},{
    name: 'AnotherModule',
    files: ['anotherModule.js']
}]);

It will load TestModule : testModule.js / testModuleCtrl.js / testModuleService.js in parallel. Once it's all done it will load AnotherModule.

Let's say that the module is defined in the first file (with angular.module('TestModule', [])) and that the second one uses angular.module('TestModule'), it will throw an error "Uncaught Error: [$injector:nomod] ..." if the second file happens to be downloaded first.

We need to define a parameter or a syntax that will make sure that certain files are loaded in order.

A parameter to force loading files in serie:

$ocLazyLoad.load([{
    name: 'TestModule',
    files: [
        'testModule.js',
        'testModuleCtrl.js',
        'testModuleService.js'
    ],
    serie: true
},{
    name: 'AnotherModule',
    files: ['anotherModule.js']
}]);

Or this kind of syntax:

$ocLazyLoad.load([{
    name: 'TestModule',
    files: [
        ['testModule.js', 'testModuleCtrl.js', 'testModuleService.js'],
        'anotherUnrelatedFile.js'
    ],
    serie: true
},{
    name: 'AnotherModule',
    files: ['anotherModule.js']
}]);

Maybe both could be implemented.

Load files in module only once

Is there any built in way to restrict a module to loading only once? Not just not reconfiguring, but knowing that a module has already been loaded and not requesting it again? We currently work around this by maintaining a list of modules we've loaded and simply don't request if we've previously loaded.

I understand that this doesn't fit every use case (like when a module is loaded piece-by-piece) but it seems to be pretty handy functionality, especially when you have dependent modules.

Controller not being initialized

I'm trying to lazy load a module. The module is injected and no errors are thrown but the controller never initializes.

My structure looks like:

/app
    /admin
        /apps
            apps.js
        admin.js
    app.js

admin.js contains the routes for all my modules that fall under the admin folder ( there is much more just shortened here ).

On init, app.js loads like:

define(['angular',
            'ui-router',
        'ocLazyLoad',
        'app/admin/admin'], function(angular){

    var app = angular.module('testapp', ['ui.router', 'oc.lazyLoad', 'admin']);

    app.config(function ($urlRouterProvider, $locationProvider, $ocLazyLoadProvider) {
        $locationProvider.html5Mode(true);

        $ocLazyLoadProvider.config({
            loadedModules: ['testapp'],
            asyncLoader: requirejs
        });
    });

    return app;
});

in my admin.js file I define all the routes for my admin section of my app like:

define(['angular'], function (angular) {

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

    module.config(function ($stateProvider, $urlRouterProvider) {

        // admin/apps/apps.js
        $stateProvider.state('apps', {
            url: '/apps',
            templateUrl: 'app/admin/apps/apps.tpl.html',
            controller: 'AppsCtrl',
            resolve: {
                apps: function (AppsModel) {
                    return AppsModel.findAll();
                },
                load: function($ocLazyLoad) {
                    return $ocLazyLoad.load({
                        name: 'admin.apps', 
                        files: ['app/admin/apps/apps']
                    });
                }
            }
        });

    return module;

});

and then in apps.js I define the apps module and controller:

define(['angular'], function (angular) {

    var module = angular.module('admin.apps', []);

    module.controller('AppsCtrl', function ($rootScope, $scope) { ... });

    return module;

});

so everything loads fine and breakpoints are even hit in the apps.js file but the controller is never init'd. The ui-view is empty like:

<div class="ng-scope" ui-view=""></div>

am i missing something or is this a bug?

Question: can I use $ocLazyLoad to load supplementary files to module that is already loaded?

What i'm looking for is to be able to lazy-load everything. After following the readme and examples, i've ended up with this skel: http://plnkr.co/edit/5XOS1jAwJsdGHzlaJBNA?p=preview

However, when I try to lazy-load only controller, to already-loaded module, I hit the module reinitialisation error, basically state reinitialisation error. In the logs you see that config is executed twice. Error fades as soon as I remove loadedModules: ['app'], line from the app.js file.

I'm still uncertain if I understand the purpose of the name property when calling '$ocLazyLoad.load()` method. What is it meant to be doing?

Thanks.

issue after merged all js resources with r.js in a requirejs project

Hi,
let me describe an issue i ran into: when i merge all js files with r.js in an Angular + ui-router + requirejs + ocLazyLoad project and try to use it without any config modifications, however the merged js is syntactically correct, ocLazyLoad.load() will incorrectly load new modules.

Problem: because the "new" module to be loaded is already defined in the merged file with all its components, the moduleExists() returns true so ocLazyLoad.load() WON'T call the register() method for that, so calling the module's components will fail.

Using the non-merged files, the issue doesn't exist cus the moduleExists() will return false so ocLazyLoad.load() will correctly load+register the new module.

(my quick workaround was, insert the line
register(providers, moduleCache, $log);
right after line 101, after row
moduleCache.push(moduleName);)

very useful plugin btw, thanks for it!

some binding not work

I have function
a class="btn btn-success btn-xs m-t-xs" ng-click="addCategoryDomain(newcategory);"> save</a

    $scope.addCategoryDomain = function(obj) {
        obj.x = {loading : 'loading'};
        data = {data1:$scope.data1,type:obj.type,name:obj.name,slug:obj.slug};
        $http.post('/url/',data).then(
          function(response,status, headers, config){
              if(response.data.success){
                obj.x.loading = 'success';
                $scope.domaincategory.unshift(response.data.rows);
                obj={};
              }
              else{
                obj.x.loading = 'failed';
              }
          },
          function(response,status, headers, config){
                obj.x.loading = 'failed';
          });
    };

I found that obj is not binding to newcategory that passed from html? in another app not using oclazyload, this code works fine..

require.js does not load dependencies from lazy loaded .js file

I just integrated ocLazyLoad to load a js file which defines AMD dependencies. Those dependencies are not loaded correctly by require.js: the ".js" suffix is not appended.

Here's my app.js (loaded itself by require.js) that contains the setup of ocLazyLoad:

define(['angular', 'components', 'lazy-load', 'ui-router', 'ui-bootstrap', 'ui-bootstrap-tpls', 'home',
    'site'], function(angular, components) {
  'use strict';

  // We must already declare most dependencies here (except for
  // common), or the submodules' routes will not be resolved
  return angular.module('app', 
    ['ui.router', 'ui.bootstrap', 'ui.bootstrap.tpls', 'search.home', 'search.site', 'oc.lazyLoad']
  )
  .config(['$ocLazyLoadProvider', function($ocLazyLoadProvider) {
    $ocLazyLoadProvider.config({
      loadedModules: ['app'],
      jsLoader: require
    });
  }])
  .run(['$ocLazyLoad', function($ocLazyLoad) {
      // components: [ {
      //   "name" : "explore",
      //   "files" : [ "/assets/javascripts/explore/main.js" ]
      // } ];
      $ocLazyLoad.load(components);
    }]);
});

The lazy loaded explore/main.js looks like this:

define(['angular', 'ui-router', './routes', './controllers'], function(angular, uiRouter, routes, controllers) {
  'use strict';
  var mod = angular.module('explore.home', ['ui.router', 'ui.bootstrap', 'ui.bootstrap.tpls', 'explore.home.routes']);
  mod.controller('HeaderCtrl', controllers.HeaderCtrl);
  mod.controller('FooterCtrl', controllers.FooterCtrl);
  return mod;
});

In the same directory there are the routes.js and controllers.js as declared as dependencies.
Unfortunately, after loading the main.js require.js loads /assets/javascripts/explore/routes and /assets/javascripts/explore/controllers, without appending the .js.

I'm using require.js 2.1.14, angular.js 1.2.16 and the latest ocLazyLoad.

Can you help with this issue?

Error on lazy load from a lazy loaded file

I have one problem. Your module works very fine, however when I try to lazy load from a lazy loaded file it says:

Error: jsLoader is not a function
this.$get</filesLoader@https : //localhost/js/angular/includes/lazyload.js:245:1

I can add the same function you have in line 104, but while the error is not showed anymore it does not load the files either... Am I doing something wrong?

angular.module("StreamApp").config(function($stateProvider, $controllerProvider, $ocLazyLoadProvider) {
    $ocLazyLoadProvider.config({
        debug: true,
        events: true
    });
    $stateProvider.state("controller", {
        url: "/:controller/:action",
        controller: function($rootScope, $state, $stateParams, $ocLazyLoad) {
            if (!$rootScope.controllers)
                $rootScope.controllers = {};

            if (!$rootScope.controllers[$stateParams.controller]) {
                $ocLazyLoad.load([{
                    files: [
                        "/js/angular/controller/" + $stateParams.controller + ".js"
                    ]
                }]).then(function() {
                    $rootScope.controllers[$stateParams.controller] = true;
                    $state.go($stateParams.controller + ( $stateParams.action ? ("." + $stateParams.action) : "" ));
                });
            }
            log($stateParams);
        }
    })
});

Brodcast module load event invoke multiple time.

Hi!

In "register" function get called with registerModules and didn't check the module is loaded or not.

e.g.:
angular.module("foo" , ["bar","bar2"]);

When it resolved the bar and bar2 is brodcasted , but when it resolve foo it call register function again
and broadcast bar and bar2 again.

I made a hot fix in line 680 with the following check:
if(regModules.indexOf(moduleName) !== -1) {
registerModules.pop();
continue;
}

Remove jQuery dependency

In the current implementation of the template loader/directive requires jQuery.
It shouldn't be to hard to remove.

We also need to check if it's used anywhere else.

$ocLazyLoadProvider.config() not loading modules defined in modules property

Hey guys,

I'm trying to use the $ocLazyLoadProvider in my app's config block to load in my modules during the config phase rather than run, but I'm finding that simply nothing is happening when I specify my modules in the config block, however the modules load just fine in the run block:

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

    // Doesn't load the routes module:
    .config(function($ocLazyLoadProvider) {
        $ocLazyLoadProvider.config({
            asyncLoader: $script
            modules: [
                { name: "myApp.routes", files: ['modules/myApp.routes.js'] }
            ]
        });
    })

    // Works just fine, but since this module is configuring routes,
    // my app doesn't work properly at this point since config phase is passed:
    .run(function($ocLazyLoad) {
        $ocLazyLoad.load( { name: 'myApp.routes', files: ['modules/myApp.routes.js'] } );
    });

Any ideas why this wouldn't be loading my module during config?

Your help would be greatly appreciated! Thanks :)

Loading json files

Is it useful to load jsons with oc? Is there an option to disable cache for them?
I tried it but plugin auto adds '.js' to end of path and returns 404.

oclazyload not work silently

I used to use angular redactor and want to move textAngular for wysiwyg but application blank without error..how to trace error?

lazy load ui router

hi, @ocombe
I just thinking if oclazyload could lazy load router for ui router, inject url to add additional url.
it would help to personalize app

HTTP Interceptors don't play well with lazy loading

Rightio, I ran into an issue when creating an HTTP interceptor to handle 401 unauthorised responses globally (ie: global logout in this case).

I eventually found that angular only evaluates (and reverses) the http interceptors array once; at the conclusion of what it considers to be the last module. Obviously this doesn't really gel well with lazy loading.

The only way I could think of to get around it was to make a change to angular itself which I'm hesitant to PR (I just don't have the spare time at the moment to properly test and submit it... that's if they'd even be interested considering we're kind of doing an end-run around the accepted way of loading modules! :-) )

You can see the changes I had to make in this commit:
https://github.com/BenBlazely/angular.js/commit/9cc372fc2e52468c4623191f1d6c5c80a49e4098

If you can think of a better way of doing it that doesn't require mod'ing angular itself, I'm all ears.

If nothing else I thought I'd put this here in case you or someone else has the same issue and needs a quick fix. (even if it is less than ideal).

B.

duplicate css, js

ui-router
when access /components/:id , add css,js file every time

        .state('components', {
            url: '/components/:id',
            resolve: {
                load: ['$ocLazyLoad','$stateParams', function ($ocLazyLoad, stateParams) {
                    return $ocLazyLoad.load({
                        name: stateParams.id,
                        files: ['some.css', 'some.js']
                    })
                }] 
            },
            templateUrl: 'some.html'
        })

$script prevent duplicate call same js not css

$ocLazyLoadProvider.config({ asyncLoader: $script }); 

I add some code to prevent duplicate css

                var checkCssArr = [];
                cssLoader = cssLoader || function(paths, callback) {
                    if (!_.contains(checkCssArr, paths[0])) {
                        checkCssArr.push(paths[0]);
                    } else {
                        paths = [];
                    }
                    var promises = [];
                    angular.forEach(paths, function loading(path) {
                        promises.push(buildElement('css', path));
                    });
                    $q.all(promises).then(function success() {
                        callback();
                    }, function error(err) {
                        callback(err);
                    });
                }

this method is not accepted jsLoader.

How can I prevent duplicate js, css?

Question: lazy load for modules with routing

I have a question. I what to build a modular application. Let's say it have a astructure like this

- app.js
- index.html
- modules
  | - default
  | - module1
  ` - module2

Inside each modules it's own structure. In app.js I create a state

.state('nav', {
    url: ':module/{path: *}',
   controller: function(){}
});

Every module has it's own navigation structure that is in module1/module1.js file. The main rule is that
all URLs have to start with module name.

Is it possible in a controller of my main nav state load that module and continue navigation? I mean trigger that module so it natively catch URL. Lets say module have state with url #/module1/users/list but module is not loaded. Then main app.js loads it and state is reevaluated so that thins justloaded module catch its URL pattern.

Possible?

controller invalid in ui-router with ocLazyLoad?

I have got a little problem when using ui-router, it looks like the controller became invalid when combine with ocLazyLoader, here is the codes:

$stateProvider
                        .state('login', {
                            url: '/login',
                            views: {
                                'lazyLoadView': {
                                    templateUrl: 'views/login.html'
                                }
                            },
                            resolve: {
                                userLogin: ['$ocLazyLoad', function($ocLazyLoad) {
                                    return $ocLazyLoad.load({
                                        name: 'app.login',
                                        files: ['js/modules/app.login.js']
                                    })
                                }]
                            },
                            controller: 'loginCtrl as login'
                            // controller: function($scope) { console.log($scope);}
                        })

The controller inside the code won't attach to the template that I loaded, I have to use ng-controller attribute inside the html template. Is it any way that I am able to use controller here or I have done something wrong?

Thanks

How to load dependences for module in proper order

Hi,

I'm learning Angular so please do not punish me :)
I wonder how to load properly service that module is using.

e.g.

$stateProvider
    .state(
    'somestate',
    {
        url: "/", // root route
        views: {
            "adminView": {
                templateUrl: '/view1.html'
            }
        },
        resolve: {
            test: ['$ocLazyLoad', function ($ocLazyLoad) {
                return $ocLazyLoad.load({
                    name: 'view1',
                    files: [
                        "assets/service.js",
                        "assets/module1.js"
                    ]
                });
            }]
        }
    });

For now module is not see service becouse of async javascript file loading.

Preload files

I was thinking about a new feature for the lib: preloading the files.

The problem is: when you use your router with ocLazyLoad to load files (with resolve) before activating the route, it delays the route until your files are loaded, and depending on your connection/files size it might take a while.
What if there was a way to preload the files when your app is idle. If you know that your user will use them later but you don't want to delay the initial loading of the page, this would be a good option.
I was even thinking that we could use web workers to do that in a separate thread to avoid slowing the app.
We would need to define an order, and some new parameters.

@BenBlazely @rolandzwaga any input on this ?

.config not called as of commit b15ec19

Module behavior has changed since the commit b15ec19

This controller lazy loads the module:

    app.controller('modulesCtrl', function ($scope, $ocLazyLoad) {

        /**
         * flag to show the the scoped div
         * @type {{ready: boolean}}
         */
        $scope.module = {
            ready: false
        };

        $scope.loadModule = function () {
            $ocLazyLoad.load({
                name: 'Utils',
                files: ['resources/modules/utils.js']
            }).then(function () {
                $scope.module.ready = true;
            });
        }
    })

The .config is no longer being invoked:

    angular.module('Utils', [])
        .config(function () {
            console.info('CONFIG block (Utils)')
        })
        .run(function () {
            console.info('RUN block (Utils)')
        })
        .service('greeter', function () {

            this.greet = "Hello From Utils Module";

            this.getGreet = function () {
                return this.greet;
            }
        })
        .controller('utilCtrl', function (greeter) {

            this.greeting = greeter.getGreet();
        })

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.