我正在查看Angular ui modal with controller in separate js file中概述的答案和问题,希望实现相同的结果,那就是将模态控制器放在其自己的controller.js文件中,只是我的主控制器是以不同的方式实现的。这是我的方式。

(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});
    }
}
})();


知道如何实现吗?

最佳答案

这可以通过两个简单的步骤完成:

步骤1:

您需要制作一个新的控制器文件并为Modal定义控制器,就像对MainController所做的那样:

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
     };

})();


第2步:

您需要在base.html(或用于包含所有脚本文件的任何文件)中包含此modal-controller.js,以便Angular知道此控制器确实存在。

08-19 03:12