使用Angular Bootstrap Modal和外部控制器

时间:2014-03-11 18:30:15

标签: javascript angularjs angular-ui-bootstrap

我正在尝试创建一个Modal,其中控制器位于外部文件中。这有助于代码组织,我当然不希望窗口对象上的控制器如Angular Bootstrap site所示的示例所示。我刚刚拿了他们的例子并将控制器移动到另一个模块,但是我收到一个控制器不存在的错误。我觉得我可能需要使用$ controller服务来检索它,但我无法让它工作。

angular.module('plunker', ['ui.bootstrap', 'otherModule'])

.controller('ModalDemoCtrl', function ($scope, $modal, $log) {

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

  $scope.open = function () {

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

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

angular.module('otherModule', [])
.controller('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');
  };
});

Plunkr here

1 个答案:

答案 0 :(得分:2)

您必须将ModalInstanceCtrl作为字符串。您正在尝试引用未定义的对象。如果controller参数是一个字符串,angular将在注册的控制器中查找它:

var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      //Needs to be a string
      controller: 'ModalInstanceCtrl',
      resolve: {
        items: function () {
          return $scope.items;
        }
      }
    });