Igor P. Igor P. - 4 months ago 17
Javascript Question

AngularJS: module inclusion among separated controllers

Assuming we have two AngularJS controllers in separate files that are included in an HTML file, like this:

//controller1.js
"use strict";
var someApp = angular.module('MYAPP');
//var someApp = angular.module('MYAPP',['ngCookies']); <-- Does not work

someApp.controller('Controller1', function($scope) {

$scope.CookieFunction = function(){
//foo
};
});


//controller2.js
"use strict";
var someApp = angular.module('MYAPP',['ngCookies','ui.bootstrap']);

someApp.controller('Controller2', function($scope,$cookies) {

$scope.SomeOtherfunction = function(){
//foo
};
});

//HTML file
<script src="controller1.js"></script>
<script src="controller2.js"></script>


Inside controller1, I'd like to perform some Cookie operation, hence need to include ngCookies. If I do so inside controller1.js, then controller2 gets undefined. I prefer to include modules exactly where I need them and not somewhere else. How can I achieve that without "erasing" subsequent controllers?

EDIT: If I move ngCookies inclusion from controller2 to controller1, I get this error message (Argument 'controller2' is not a function, got undefined)

Answer

The problem in the code example is following (change [ngCookies] to ['ngCookies'])

//controller1.js
"use strict";
var someApp = angular.module('MYAPP',['ngCookies']);

Other approach, simplifying to 1 app.js

// app.js
"use strict";
var someApp = angular.module('MYAPP',['ngCookies']); 

someApp.controller('Controller1', function($scope) {

    $scope.CookieFunction = function(){
        //foo
    };
});   

someApp.controller('Controller2', function($scope,$cookies) {

    $scope.SomeOtherfunction = function(){
        //foo
    };
}); 

//HTML file
<script src="app.js"></script>

Simplify to 1 main app.js with different controller files

If you want to keep controllers in separate file then,

app.js

var app = angular.module("testApp",['ngCookies','ui.bootstrap']);

test1.js

app.controller("controller1",function(){
// some code
})

test2.js

app.controller("controller2",function(){
// some code
})

Finally include js files in html

<script src="app.js"></script>
<script src="controller1.js"></script>
<script src="controller2.js"></script>