1

我一直在玩从工厂使用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); 
    }; 
    }); 
+0

希望你能从控制器使用d访问数据ialogService.newObj变量。 –

回答

1

你可以使用上$uibModalInstance服务提供close方法,您可以在其中传递数据,同时关闭弹出窗口。然后你可以利用result承诺对象,它会在模态被关闭时被调用。无论从$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' } 
}); 

模态控制器

$scope.cancel = function() { 
    $uibModalInstance.close({data: 'MyCustomData'}); 
}; 
+1

应该从服务方法 – charlietfl

+0

@charlietfl返回'$ uibModal.open()'实例感谢您的支持,更新回答:-) –

+0

也为更通用的使用可以返回'modalInstance.result'。然后控制器只管理承诺 – charlietfl