3

In my AngularJS app I have over 15 controllers, services...etc which I am currently including them all in index.html which include ng-view, so I was wondering is there a way to include only the controllers, services of the current loaded route? Instead of including all controllers, services for all routes all the time? Thanks

3
  • 1
    Lookup using requireJS with angularJS Commented Mar 20, 2014 at 17:54
  • @dave Isn't there any AngularJS approach? RequireJS looks great but I am hoping for more of an AngularJS approach to solve the problem. Thanks Commented Mar 20, 2014 at 18:19
  • Angular does not support lazy loading as of version 1.x, it will be from 2.0... for now, you can take a look at github.com/vojtajina/ng-1.x-async-hack or github.com/doodeec/ng-1.x-async-hack/tree/multiple_lazy_files Commented Mar 20, 2014 at 20:46

1 Answer 1

1

The AngularJS approach is to load them all beforehand. You could probably do something like

$routeProvider
  .when('/home',
    {
        templateUrl: '/app/views/home.html',
        resolve: resolveController('/app/controllers/homeController.js')
    });

And then resolveController would return a promise.It would load the scriptwith the controller and resolve the promise once the load is complete. Something like

app.config(['$routeProvider',
    function($routeProvider) {
        var resolveController = function(path) {
            var deferred = $q.defer();
            var script = document.createElement('script');
            script.src = path;
            script.onload = function() {
                $scope.$apply(deferred.resolve());
            };
            document.body.appendChild(script);
            return deferred.promise;
        };
        $routeProvider.when('/home', function() { /*...*/ } );
    }
);

There could be syntax errors as I haven't even tried this, but this is what I would probably try if I wanted to do it.

Sign up to request clarification or add additional context in comments.

2 Comments

In which controller funtion resolveController(path) has to be written ?
I get an error at $scope.$apply(deferred.resolve()); : $scope.$apply is not a function and before this I get angular-1.5.8.js:13920 Error: [ng:areq] Argument 'fn' is not a function, got Object. I'm using ui-router

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.