使用$uibModal从工厂

Using $uibModal from a factory

本文关键字:工厂 uibModal 使用      更新时间:2023-09-26

我一直在玩使用uibModal从工厂,而不是使用它从我的控制器。对话框出现,字段数据在OK单击时返回到服务,但是,我不知道如何将数据返回到我的控制器,它将被添加到我的模型有指针吗?

下面是我的工厂代码:

    'use strict';
angular.module('ngTableScopeApp')
.factory('DialogService', function($uibModal){
  var DialogService = {};
  DialogService.newObj = {};
  DialogService.addNewItem = function(template, $q){
    this.modalInstance = $uibModal.open({
      templateUrl: template,
      controller: function($scope, $uibModalInstance){
        $scope.ok = function () {
          $uibModalInstance.close($scope);
          return this.newObj;
        };
        $scope.cancel = function () {
          $uibModalInstance.dismiss('cancel');
          return null;
        };
      }
    });
  };
  return DialogService;
});

控制器代码:

    'use strict';
/**
 * @ngdoc function
 * @name ngTableScopeApp.controller:MainCtrl
 * @description
 * # MainCtrl
 * Controller of the ngTableScopeApp
 */
angular.module('ngTableScopeApp')
  .controller('MainCtrl', function (NgTableParams, DummyData, DialogService) {
    var self = this;
    self.data = DummyData.generateData(1);
    var createUsingFullOptions = function() {
      var initialParams = {
        count: 10 // initial page size
      };
      var initialSettings = {
        // page size buttons (right set of buttons in demo)
        counts: [5, 10, 25, 50],
        // determines the pager buttons (left set of buttons in demo)
        paginationMaxBlocks: 13,
        paginationMinBlocks: 2,
        dataset: self.data //DummyData.generateData(1)
      };
      return new NgTableParams(initialParams, initialSettings);
    };
    self.customConfigParams = createUsingFullOptions();
    self.addNewItem = function(){
        DialogService.addNewItem('views/addNewItem.html', self);
    };
  });

您可以使用$uibModalInstance服务上可用的close方法,其中您可以在关闭弹出窗口时传递数据。然后你可以利用result promise对象它会在modal关闭时被调用。从$uibModalInstance.close方法传递的任何数据都在这里可用。请确保您正在返回$uibModal.open方法返回的承诺。

DialogService.addNewItem = function(template, $q){
    this.modalInstance = $uibModal.open({
          templateUrl: template,
          controller: function($scope, $uibModalInstance){
            $scope.ok = function () {
               $uibModalInstance.close({ data: 'OK Called' });
            };
            $scope.cancel = function () {
               $uibModalInstance.close({ data: 'Cancel Called' });
            };
          }
        });
    };
    return this.modalInstance;
};
控制器

DialogService.addNewItem('views/addNewItem.html', self)
.result.then(function(data) {
   console.log("data", data); // print { data: 'MyCustomData' }
});
<<p> 模态控制器/strong>
$scope.cancel = function () {
    $uibModalInstance.close({data: 'MyCustomData'});
};