Robert van der Spek Robert van der Spek - 4 months ago 8
AngularJS Question

Can a controller be in a seperate file when using ng-view?

Currently I am learning AngularJS. I have made a 'hello world' app that displays through the ng-view directive. So far so good!

My files are ordered in this fashion:

- WebContent *(root)*
> - controllers *(folder)*
>> - controllers.js
> - views *(folder)*
>> - view1.html
>> - view2.html
> - index.html


The route config looks like this:

function routeConfig($routeProvider){
$routeProvider.when('/',
{
templateUrl: "views/view1.html",
controller: "View1Ctrl"
}
).when("/view/:id",
{
templateUrl: "views/view2.html",
controller: "View2Ctrl"
}
).otherwise(
{
redirectTo: "/"
});
};

app.controller("View1Ctrl", function($scope) {
$scope.message = "Hello World1";
}
[... etc. ...]


As I've mentioned before: this works perfectly fine. However, things might get more complex. The controllers could contains more functions etc. Is it possible to put these controllers in external files? So it would look something like this:

- WebContent *(root)*
> - controllers *(folder)*
>> - controllers.js
>> - view1-controller.js
>> - view2-controller.js
> - views *(folder)*
>> - view1.html
>> - view2.html
> - index.html


I already tried to simply import these files into the index:

<script src="controllers/view1-controller.js"></script>


But this did not seem to work. (It left me with a blanc page.) Hoping someone can help me out!

Answer

Dag Robert,

That certainly possible, even more I would recommend it! I'd like to refer you to this Plunkr

Basically you can just do something like this:

(function() {
  angular
    .module('plunker')
    .directive('helloWorld', function() {
      return {
        scope: true,
        restrict: 'E',
        controller: 'HelloWorldController',
        controllerAs: '$ctrl',
        templateUrl: 'app/directives/hello-world/template.html'
      };
    })
})();

Important notes:

  • To create a new module, you write: angular.module('name', dependencies);. Where the dependencies are an array.
  • To retrieve the same module you don't write the dependencies: angular.module('name'). This will simply get the module