noobcoder noobcoder - 1 year ago 97
AngularJS Question

Angular ModalController to be its own file

I was looking at the answer and question outlined in Angular ui modal with controller in separate js file and I wish to achieve the same outcome, that is have the modal controller in its own controller.js file, just that my main controller is implemented in a different way. Here is how I have it.

(function () {
.controller('MainController', MainController);

var ACTION = {

MainController.$inject = ['$rootScope', '$modal'];
function MainController($rootScope, $modal) {
var vm = this;
vm.method1 = method1;
vm.method2 = method2;

function method1(){
var modalInstance = createModal();
// do something....

function createModal(){
return ${
templateUrl: 'app/someModalFile.html',
controller: 'ModalController as vm',
resolve: {
action: function(){
return vm.action;
someVar: function() {
return vm.someVar.obj;
anotherVar: function(){
return vm.anotherVar;
// I want to have this in a separate controller file and
// use the MainController to invoke this modal controller.
function ModalController($modalInstance, someVar, anotherVar){
var vm = this;

vm.confirm = confirm;
vm.cancel = cancel;
vm.someVar = someVar; // to display on the modal window
vm.anotherVar = anotherVar;

function confirm(){
$modalInstance.close({action: ACTION.CONFIRM});

function cancel(){
$modalInstance.close({action: ACTION.CANCEL});

Any idea how to achieve this ?

Answer Source

This can be done in two easy steps:


You need to make a new controller file and define the controller for Modal just as you did for MainController as:


     //you can get rid of the ModalController you have defined in the same file and rather use this
            .controller('ModalController', ModalController);

     ModalController.$inject = ['$modalInstance', 'someVar', AnotherVar];

     function ModalController($modalInstance, someVar, AnotherVar){
          //code here



You need to include this modal-controller.js in your base.html (or whichever file you are using to include all script files) so that Angular knows that this controller actually exists.

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