无法在AngularJS中为部分视图注入控制器

时间:2014-07-12 17:03:34

标签: javascript angularjs

我想创建弹出模式,我的控制器必须依赖另一个控制器。

下面是我的主控制器文件product.js来定义模态实例。我正在使用angular-UI的帮助

    var myStoreControllers=angular.module("myStoreController",['ui.bootstrap','myStoreModalController']);

    myStoreControllers.controller('myStoreProductCtrl',function($scope,$modal,$log,ModalInstanceCtrl){

     $scope.message="Checking routing 123";


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

      $scope.open = function (size) {

        var modalInstance = $modal.open({
          templateUrl: 'assets/app/views/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());
        });
      };


    });


Below is my controller definition for the view.

var myStoreModalController=angular.module("myStoreModalController",[]);

myStoreModalController.controller('ModalInstanceCtrl',function($scope, $modalInstance, items){

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

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

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

});

这一直给我错误:

Error: [$injector:unpr] Unknown provider: ModalInstanceCtrlProvider <- ModalInstanceCtrl

我无法理解为什么这种依赖注入失败。

1 个答案:

答案 0 :(得分:0)

我根据Cory Suggested做了更改,并且工作正常。

精炼代码如下:

 var myStoreControllers=angular.module("myStoreController",['ui.bootstrap','myStoreModalController']);

    myStoreControllers.controller('myStoreProductCtrl',function($scope,$modal,$log,ModalInstanceCtrl){

     $scope.message="Checking routing 123";


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

      $scope.open = function (size) {

        var modalInstance = $modal.open({
          templateUrl: 'assets/app/views/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());
        });
      };


    });


Below is my controller definition for the view.

var myStoreModalController=angular.module("myStoreModalController",[]);

myStoreModalController.controller('ModalInstanceCtrl',function($scope, $modalInstance, items){

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

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

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

});