Angularjs - 一个控制器中的 Angular UI $modal 和 $modalInstance

Ken*_*Yap 5 angularjs angular-ui

我想问一下,我知道AngularUI的模态由2个控制器组成,1是我用来处理数据的默认控制器,另一个是处理$modelInstances,这对我来说很好。但是我想要做的是在我的模态显示中渲染/编辑数据时我将使用几个范围。我试图做的不是在控制器之间解决所有这些范围,而是将两个控制器合并在一起,以便可以在网页之间共享范围。(注意它是一个实时范围)我所做的如下

angular.module('app', ['ngAnimate', 'ui.bootstrap']);
angular.module('app').controller('ModelCtrl', function ($scope, $modal, $modalInstance) {

  $scope.items = ['item1', 'item2', 'item3'];
  //I have a few more scopes to be used in the model

  $scope.open = function (size) {

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

    modalInstance.result.then(function () {

    }, function () {

    });
  };

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

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
});
Run Code Online (Sandbox Code Playgroud)

我已经将两个控制器合二为一,并将相关模块注入回去,这样理论上它就可以工作了。但相反,我得到的是一个错误说[$injector:unpr] Unknown provider: $modalInstanceProvider <- $modalInstance <- ModelCtrl. 从这个错误中理解,这意味着我注入了一个未知的提供者,$modalInstanceProvider所以我试图从模块中删除 $modalInstance,Modal 设法打开,但操作closedismiss抛出了$modalInstance is not defined. 我做错了什么,我应该如何组合两个控制器而不是将它们分成 2 个?

这是plunkr链接,因此您可以理解我的意思。谢谢你。

小智 2

您不必为创建的模态创建新的控制器,只需执行以下操作:

angular.module('app').controller('ModelCtrl', function ($scope, $modal) {

看到我没有注射$modalInstance

那么模态创建就像:

var modalInstance = $modal.open({
  animation: true,
  templateUrl: 'myModalContent.html',
  size: 'lg',
  scope: $scope, //i make modal scope the same as  ModelCtrl scope
});
Run Code Online (Sandbox Code Playgroud)

然后你用modalInstance你创建的来操纵模态

所以最终代码是

angular.module('app', ['ngAnimate', 'ui.bootstrap']);
angular.module('app').controller('ModelCtrl', function ($scope, $modal) {

  $scope.items = ['item1', 'item2', 'item3'];
  //I have a few more scopes to be used in the model

  $scope.open = function (size) {

    var modalInstance = $modal.open({
      animation: true,
      templateUrl: 'myModalContent.html',
      size: 'lg',
      scope: $scope
    });

    modalInstance.result.then(function () {

    }, function () {

    });
  };

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

  $scope.cancel = function () {
    modalInstance.dismiss('cancel');
  };
});
Run Code Online (Sandbox Code Playgroud)