noobcoder noobcoder - 4 months ago 8
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 () {
angular.module('app.mainModule')
.controller('MainController', MainController);

var ACTION = {
CANCEL: 0,
CONFIRM: 1
};

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 $modal.open({
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

This can be done in two easy steps:

Step1:

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

modal-controller.js

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

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

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

})();

Step2:

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.