一尘不染

将$ uibModalInstance注入到不是由$ uibModal启动的控件中

angularjs

我有以下两种观点:

1)foo.html

  <p>Hello {{name}}</p>

2)foo-as-modal.html

<div class="modal-header">
    <h3 class="modal-title">I'm a modal</h3>
</div>
<div class="modal-body">
    <ng-include src="'foo.html'"></ng-include>
</div>
<div class="modal-footer">
    <button class="btn btn-default" ng-click="cancel()">Close</button>
</div>

foo.html的控制器是fooController

angular.module('myApp').controller('fooController', ['$scope','$uibModalInstance', function($scope,$uibModalInstance) {

     $scope.name = "John"

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

我需要注入$uibModalInstancefooController.dismiss工作

当我foo-as-modal.html作为模式调用时,效果很好,即:

    var modalInstance = $uibModal.open({
        templateUrl: 'foo-as-modal.html',
        controller: 'fooController',
        scope: $scope.$new(),
        size: 'lg'
    });

但是当我foo.html以普通视图(通过$routeProviderng-view指令)调用时,它会引发错误,即:

    .when('/foo', {
        templateUrl: 'foo.html',
        controller: 'fooController'
    })

错误是:

 Error: [$injector:unpr] Unknown provider: $uibModalInstanceProvider <- $uibModalInstance <- fooController

而且该视图不显示“ John”(由于错误)

我该如何解决?我真的需要重用,foo.html并且fooController作为模态和非模态,因为它们有很多东西(在这里我已经简化了)


编辑:这是一个笨拙的人:

https://plnkr.co/edit/9rfHtE0PHXPhC5Kcyb7P


阅读 403

收藏
2020-07-04

共1个答案

一尘不染

好吧,我这样解决了:

  1. 删除了注射$uibModalInstancefooController
  2. 调用模态时, 我将modalInstance作为变量传递给模态的范围:
        var modalScope = $scope.$new();

    var modalInstance = $uibModal.open({
        templateUrl: 'foo-as-modal.html',
        controller: 'fooController',
        scope: modalScope
    });

    modalScope.modalInstance = modalInstance;
  1. 使用范围变量关闭模态:
    $scope.modalInstance.dismiss('cancel');  // instead of $uibModalInstance.dismiss(..)
    

这是原始plunkr的分支,带有以下解决方案:https
://plnkr.co/edit/ZasHQhl6M5cCc9yaZTd5

2020-07-04