简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM