How to separate controllers in different files for angularjs?

时间:2015-09-14 15:28:34

标签: javascript html angularjs

I have a globale routes controller and want to create an additional controller for each page template.

It's done as follows:

var app = angular.module('myapp', ['ngSanitize', 'ngRoute']);

app.config(function($routeProvider){
    $routeProvider
        .when("/test", {
            templateUrl:    "./templates/test.html",
            controller:     "testController"
        })
});

app.controller('test', function() {
    //...
});

Question: how can I move the controller to it's own testController.js file? I tried it, but then the controller does not work anymore.

Which steps do I have to take if I extract the controller in its own file?

  1. How can I get access to var app module variable from within testController.js?
  2. Do I necessairly have to include each controller as new <script src="js/testController.js"></script> tag entry in my html templates? That would be cumbersome, as I want to split my application into many controllers, and that would result in many many imports.

1 个答案:

答案 0 :(得分:5)

You can access app by simply declaring it without dependencies:

var app = angular.module('myapp');
app.controller("testController", function() {

});

And yes, you need to include testController.js on every page that needs it.