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
-
1Lookup using requireJS with angularJSdave– dave2014-03-20 17:54:29 +00:00Commented 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. ThanksMChan– MChan2014-03-20 18:19:31 +00:00Commented 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_filesdoodeec– doodeec2014-03-20 20:46:55 +00:00Commented Mar 20, 2014 at 20:46
Add a comment
|
1 Answer
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.
2 Comments
Rajesh
In which controller funtion resolveController(path) has to be written ?
sTx
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