【问题标题】:using a modal to invoke a function from the parent scope (angular)使用模态从父范围调用函数(角度)
【发布时间】:2025-12-17 06:55:01
【问题描述】:

我有一个 main.controller.js,在该控制器中,我有一个模式,我想用它来通知用户警告,然后再继续应用程序的其余部分。

例如...我想从模态调用我的 fileNew 函数

main.controller.js:

    $scope.warningModal = function() {
                $modal.open({
                  animation: true,
                  templateUrl: "./modal.html",
                  controller: "modalController",
                });
          };
    $scope.fileNew = function(type, subject, application) {
        newApplication(type, subject, application)
          $state.go('submissions');
        });
      };

main.html:

<li><a ng-click="warningModal()">New app</a></li>

modal.html:

<div class="modal-body">
  <p>warning message</p>
</div>
<div class="modal-footer clearfix">
  <button class="pull-right btn btn-primary" ng-click="$parent.fileNew()">Continue</button>
</div>

模态控制器:

$scope.$parent.fileNew();

在控制台中给我一条警告消息说..$scope.$parent.fileNew 不是一个函数。

有什么想法吗?

编辑:

关于这个想法的另一个快速问题...

我有 3 种不同类型的文件我要提交的新应用程序...

所以在我的主 controller.js 中:

$scope.fileNew = function(type, subject, application) {
        newApplication(type, subject, application)
          $state.go('submissions');
        });
      };
$scope.fileOld = function(type, subject, application) {
        newApplication(type, subject, application)
          $state.go('submissions');
        });
      };
$scope.fileEdit = function(type, subject, application) {
        newApplication(type, subject, application)
          $state.go('submissions');
        });
      };

有什么方法可以让我通过点击哪个按钮来获得模态框上的同一个继续按钮?

【问题讨论】:

    标签: javascript angularjs angularjs-scope modal-dialog


    【解决方案1】:

    在最新版本的 Angular UI Bootstrap 中,您可以包含 scope 选项,您可以在其中传递您希望在模态控制器中可用的范围:

    $scope.warningModal = function() {
      $modal.open({
         animation: true,
         scope: $scope,
         templateUrl: "./modal.html",
         controller: "modalController",
      });
    };
    

    所以现在您可以从modalController 中调用您的函数:

    $scope.fileNew(type, subject, application);
    

    【讨论】:

    • 所以我可以在模态控制器中调用 $scope.fileNew 吗?
    • 是的!不过,请检查您的版本号。这个功能是相当新的。