Angular-UI 的全局模态

Global modals with Angular-UI

我想知道是否有可能将模态调用代码移出工作文档并从一些普通工厂调用它们。

目前我调用对话:

vm.showObjectInfo = function () {
    $rootScope.mObjectInfoInstance = $uibModal.open({
        animation: true,
        templateUrl: 'frmObjectInfo.html',
        backdrop: 'static',
        keyboard: false
    });

    $rootScope.mObjectInfoInstance.result.then(function () {
        // Refresh something in this document
    });
};

这种方法的缺点是我需要在每个我想调用对话框的文件中编写这段代码,这意味着我创建了相同事物的更多实例。

我想知道也许我可以将 $rootScope.mObjectInfoInstance 代码移动到一些常见的工厂并使用:

vm.showObjectInfo = function () {
    myFactory.objDialog.result.then(function () {
        // Refresh something in this document
    });
};

我尝试这样做,但每次我都以 undefined objDialog 结束,如果说实话,我认为我无论如何都做错了。

有什么建议,或者一些建议"best practice using common dialogs"?

谢谢

您可以在工厂中打开模态逻辑:

factory('ModalService', function($uibModal){

    function openModal(options){
         var modalInstance= $uibModal.open(options);
         return modalInstance.result;
    }

    return {
        openModal: openModal
    }

})



//in controller:
vm.showObjectInfo = function () {

     ModalService.openModal({
        animation: true,
        templateUrl: 'frmObjectInfo.html',
        backdrop: 'static',
        keyboard: false
     }).then(function(){
        // Refresh something in this document
     })

};

我解决了这个问题,我使用全局 JS 变量来保存模态实例,它使代码非常干净和轻便:

这里是demo plnkr

代码如下:

var myApp = angular.module('Shared', ['ui.bootstrap']);    

// Create simple global var for holding modal instance outside of angular!
var GmObjectInfoInstance;

myApp.factory('sh', function($uibModal){
    // Implement openModal in your shared factory
    function openModal(page){
        return $uibModal.open({
            animation: true,
            templateUrl: page,
            backdrop: 'static',
            keyboard: false
        });       
    }
    // Expose function
    return {
        openModal: openModal
    }
});


myApp.controller('frm', ['sh', function (sh) {
  this.showObjectInfo = function () {

      // Call in any controller or factory or whatever
      GmObjectInfoInstance = sh.openModal("frmObjectInfo.html");
      GmObjectInfoInstance.result.then(function () {
         console.log("blah");
      });

  }

}]);


myApp.controller('modalCtrl', [ function () {
   // To close the dialog from inside, just use
   this.onCancelBtnClick = function(){
      GmObjectInfoInstance.close();
}       
}]);

所以你不需要多次使用$rootScope和重写代码,我觉得这个方法非常有用。