Ali Raza Ali Raza - 1 year ago 111
AngularJS Question

How to define controllers in multiple files - AngularJs

I am trying to define controllers in separate files, but I'm getting the error:

transactionsController not a function got undefined

File structure

I have added files in this sequence
1- common.js
2- transactions.js

In common files I have defined

var app = angular.module("spModule", ["ngMessages", "ui.bootstrap"]);


['$scope', '$http', function ($scope, $http) {} ]


<body ng-app="spModule" ng-controller="transactionsController">

Answer Source

First, you should get rid of the global app variable. This is not necessary. Second, you have to understand the principle of the angular.module() method.

Using angular.module() with two parameters (e.g. angular.module('my-module', [])) would result in setting a new module with its corresponding dependencies. In contrast, when using angular.module('my-module') the corresponding module is looked up internally and returned to the caller (getting).

The means when you first define you application you might just create the following files and structure.


angular.module('myApp', []);


angular.module('myApp').controller('FirstController', function () {});


angular.module('myApp').controller('SecondController', function () {});

If you now include these files in your html document in this particularly order (at least app.js has to come first), your application works just fine with two separate controllers in two separate files.

Further readings

I can recommend the AngularJS Styleguide on modules for getting more ideas on this topic.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download