Search code examples
angularjsangular-ui

How to deal with modal controller outside AngularJs module?


My app uses Angular UI to deal with modals and I think I found a problem, as below:

I have a controller that calls the modal controller:

angular.module('MyApp').controller('MainCtrl', function ($scope, $modal) {
    $scope.openModal = function () {
        var myModal = $modal.open({
            animation: true,
            templateUrl: 'ModalContent.html',
            controller: ModalCtrl
        });
    };
});

I also have the modal controller in another file, as a simple function:

function ModalCtrl ($scope, $modalInstance) {
    $scope.ok = function () {
        $modalInstance.close();
    };

    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
};

It's working well, but I think the modal controller have to be inside AngularJs module. The questions are:

  • Can I do it and keep the modal controller in a separated file?
  • It's a good practice keep the modal controller outside AngularJs module?
  • What is the best practice to reuse a modal controller in many pages?

Thanks a lot!


Solution

  • That object you're passing into $modal.open() can be registered as a shared service and the modal controller can be embedded right inside it.

    angular.module('myApp').factory('myModalConfig', function() {
    
        return {
            animation: true,
            templateUrl: 'ModalContent.html',
            controller: function($scope, $modalInstance) {
                $scope.ok = function () {
                    $modalInstance.close();
                };
    
                $scope.cancel = function () {
                    $modalInstance.dismiss('cancel');
                };
            }
        };
    
    });
    

    Then just inject that along with the $modal service and pass it.

    angular.module('MyApp').controller('MainCtrl', function ($scope, $modal, myModalConfig) {
        $scope.openModal = function () {
            var myModal = $modal.open(myModalConfig);
        };
    });
    

    I go further than this myself and wrap the whole thing into a custom modal service factory, so I can just inject one thing and open modals like this: profileModals.editProfile(). But that's beyond the scope of this answer.