Angular bootstrap模式如何从模态的ok函数调用服务?

时间:2014-08-18 10:51:52

标签: angularjs twitter-bootstrap

我已实施Angular Bootstrap Modal。下面是它的角度代码

var ModalDemoCtrl = function ($scope, $modal, $log) {

  $scope.items = ['item1', 'item2', 'item3'];

  $scope.open = function (size) {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: ModalInstanceCtrl,
      size: size,
      resolve: {
        items: function () {
          return $scope.items;
        }
      }
    });

    modalInstance.result.then(function (selectedItem) {
      $scope.selected = selectedItem;
    }, function () {
      $log.info('Modal dismissed at: ' + new Date());
    });
  };
};

// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.

var ModalInstanceCtrl = function ($scope, $modalInstance, items) {

  $scope.items = items;
  $scope.selected = {
    item: $scope.items[0]
  };

  $scope.ok = function () {
    $modalInstance.close($scope.selected.item);
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
};

这很好。

我的问题是如何在模态控制器中使用服务?在ok函数中,我想进行服务调用并保存一些细节并使用成功和错误回调。

我不知道该怎么做。

1 个答案:

答案 0 :(得分:2)

您只需通过控制器构造函数注入依赖项,即:

var ModalInstanceCtrl = function ($scope, $modalInstance, items, MyService) {

$scope.ok = function () {
    MyService.doSomething();
    $modalInstance.close($scope.selected.item);
};