关注下载 link 并关闭模式?

Follow download link and dismiss modal?

我继承了一个用 Angular 编写的 GUI,目前我什至不知道 trim 到 fiddle。所以我希望这比快速 Google 上出现的更直接。

我有一个使用 Bootstrap 创建的模态对话框,与此处的现场演示基本相同:http://getbootstrap.com/javascript/

来源的副本 link:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

我的主要区别在于 "Save Changes" 按钮实际上是一个 link - 指向无需离开页面即可下载的资源。它看起来像这样:

<a ng-href="{{downloadUrl}}" class="btn btn-primary">Download</a>

我的目标是在单击 link 时关闭上述模式对话框,同时仍在下载文件。如果我使用 data-dismiss,下载不会发生。

如果我需要深入研究代码,那很好,但我希望对模板进行简单的更改就可以解决问题。有什么建议吗?

您必须自己关闭模态。这是没有 angular 的仅 bootstrap.js 解决方案。在 angular 中,您将使用 angular-bootstrap 打开模态窗口,然后也以这种方式关闭它。

<a ng-href="some-reosource-url" target="_blank" class="btn btn-primary" onClick="closeModal()">Download</a>

function closeModal() {
  $('#myModal').modal('hide');
}

http://plnkr.co/edit/0sRb5VdT9isEFdJ66Rxe?p=preview

这是一个有效的 Plunker

JS

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.hideAndDownload = function() {
    $('#myModal').modal('hide');

    var link = document.createElement("a");
    link.download = "data:text/html";
    link.href = "http://code.jquery.com/jquery-1.11.3.min.js";
    link.click();
  }
});

标记

        <button type="button" class="btn btn-primary" ng-click="hideAndDownload()">Save changes</button>

首先,与 AngularJS 1.x 一起使用时,始终使用 Bootstrap UI.


当使用 Bootstrap UI 的 $uibModal 时,操作模态以及在视图和模态之间传递数据要容易得多。 link 不起作用的原因是模态应该先关闭。

您可以创建一个简单的函数来替换 hrefng-href:它首先关闭模态 ,然后转到 link .

并且,请记住,请不要使用 jQuery,并始终尝试使用 AngularJS 依赖项,例如 $window 而不是 window,当它们可用时。这也适用于 onclick。始终使用 ng-click,并在控制器中处理逻辑。


在您的模板中,添加控制器和一个 ng-click 属性:

<div ng-controller="MyCtrl as $ctrl">
    <a href target="_blank" class="btn btn-primary" ng-click="$ctrl.go('#/some/url')"> Go </a>
</div>

在您的控制器中,添加用于关闭模式的逻辑,并遵循 link:

app.controller('MyCtrl', function($uibModalStack, $window) {
    this.go = function(path) {
        $uibModalStack.dismissAll();
        $window.location.href = path;
    }
})