本文介绍了将$ uibModalInstance注入到不是由$ uibModal启动的控件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两种观点:

1)foo.html

1) foo.html

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

2)foo-as-modal.html

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:

The controller for foo.html is fooController:

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

     $scope.name = "John"

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

我需要将$uibModalInstance注入到fooController.dismiss才能正常工作

I need to inject $uibModalInstance to fooController for the .dismiss to work

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

That works great when I invoke foo-as-modal.html as a modal, ie:

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

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

But it throws error when I invoke foo.html as a normal view (via $routeProvider and ng-view directive), ie:

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

错误是:

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

由于错误,该视图不显示"John"

And the view doesn't display "John" (because of the error)

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

How can I solve this? I really NEED to reuse foo.html and fooController as a modal and non-modal, because they have lots of stuff (I've simplified here)

这是一个笨拙的人:

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

推荐答案

我以这种方式解决了

  1. fooController
  2. 中删除了注入$uibModalInstance
  3. 在调用模式时,我将modalInstance作为变量传递给模式的范围:

var modalScope = $scope.$new();

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

modalScope.modalInstance = modalInstance;

  • 使用范围变量关闭模态:

  • Dismiss the modal with the scope variable:

    $scope.modalInstance.dismiss('cancel');  // instead of $uibModalInstance.dismiss(..)
    

  • 这里是原始plunkr的分支,它具有以下解决方案: https://plnkr.co/edit/ZasHQhl6M5cCcc9yaZTd5

    Here is a fork of the original plunkr, with this solution: https://plnkr.co/edit/ZasHQhl6M5cCc9yaZTd5

    这篇关于将$ uibModalInstance注入到不是由$ uibModal启动的控件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    11-01 20:58