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