Matt
Matt

Reputation: 26971

Using ng-view and loading the controller on demand

I am using ng-view in an attempt to re-use common page elements. Perhaps I am mis-understanding the point of view and it's not appropriate here.

Basically, I have an html page that looks like this:

<html>
    <head>
        <!-- css and js here including index.js -->
    </head>
    <body ng-app="app" ng-controller="ctrl">
        <navigation-bar/>
        <div ng-view />
    </body>
</html>

Here is what my index.js looks like

(function () {
    angular.module('app', ['ngRoute', 'ngSanitize'], function ($routeProvider) {});
    angular.module('app').controller("ctrl", function ($scope, $log, $q, $timeout) {});
    angular.module('app').config(["$routeProvider", function ($routeProvider) {
                $routeProvider.when("/management", {
                    templateUrl : "/experiment/management.html",
                    // Is there a way to load /experiment/managementController.js here?
                }
                })
            ]);
    })();

My management.html

<div ng-controller="managementController">
<!-- A bunch of code -->
</div>

And managementController.js (which I would like to run only when the route is loaded)

(function () {
    angular.module('app').controller("managementController", [
            "$scope", "$sce", "$log", function ($scope, $sce, $log) {
                // controller specific code
            }
        ]);
})();

Why do I want to do this? Because I have many, many potential views with many potential controllers. (On the order of 50)

Is this not possible or not the intent of ng-view?

If it's not the intent of ng-view, is there something that could help me in this case?

Upvotes: 0

Views: 2190

Answers (2)

sahil gupta
sahil gupta

Reputation: 2349

You can use resolve property in angular Js which can handle dynamically loading the script containing the target controller and resolve the promise once the load is complete.

for example:

$routeProvider
    .when('/management',
        {
            templateUrl: '/experiment/management.html',
            resolve: resolveController('/app/controllers/managementController.js')
        }); 

Upvotes: 1

ODelibalta
ODelibalta

Reputation: 2244

Take a look at the first example in the docs. Check out the script.js tab.

$routeProvider.when("/management", {
                    templateUrl : "/experiment/management.html",
                    controller: 'managementController',

                }

If you meant that you want to load the actual file, take a look at this post

Upvotes: 1

Related Questions