Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Include scripts based on current route

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

like image 737
MChan Avatar asked Dec 03 '25 01:12

MChan


1 Answers

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.

like image 81
dave Avatar answered Dec 05 '25 16:12

dave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!