简体   繁体   English

在更改角度路线时,Bootstrap Modal无法正确关闭

[英]Bootstrap Modal isn't closing properly on angular route change

I am using Angular (the $routeProvider, not ui-route), and I have a bug when I have a modal open and try to change the route. 我正在使用Angular($ routeProvider,而不是ui-route),当我打开模态并尝试更改路线时遇到错误。

On the route change, since the modal is still open, two bugs happen: 1) I can't scroll. 在更改路线时,由于模式仍处于打开状态,因此会发生两个错误:1)我无法滚动。 2) The opacity is at 0.5. 2)不透明度为0.5。

What seems to be happening is the routed event is firing before my jQuery.hide. 似乎正在发生的是在我的jQuery.hide之前触发了路由事件。

I have a workaround, but I feel like this way sucks. 我有一个解决方法,但是我觉得这种方式很糟糕。

The modal includes two relevant things. 模态包括两个相关的东西。

One is a static link. 一个是静态链接。 I did this: 我这样做:

// This catches the click on signup from the modal, closes the modal, then
// continues the route change.
$('#modal-signup-link').click(function(event) {
  event.preventDefault();
  $('#login-modal').modal('hide');
  $location.path('/signup');
});

Basically, I created a jQuery on click handler. 基本上,我在点击处理程序上创建了一个jQuery。 Works well. 效果很好。

The second portion of the modal allows a user to log in, and I use a service to call the API request. 模式的第二部分允许用户登录,并且我使用服务来调用API请求。 This one required me to use the $timeout to delay the route change (and it seems to work). 这需要我使用$ timeout来延迟路由更改(它似乎可以工作)。 I feel like this is a BAD solution. 我觉得这是一个糟糕的解决方案。

$scope.submit=function() {
  console.log('Submit');
  Login.login($scope.username, $scope.password).then(function(data) {
    if (data.id) {
      $('#login-modal').modal('hide');
      $timeout(function() {
        $location.path('/games');
      }, 500)
    } else {
      $scope.loginData = data.errors.password;
      $scope.loginError = true;
      $timeout(function() {
        $scope.loginError = false;
      }, 6000)
    }
  });
};

Ignore the bottom portion, that's just for handling errors. 忽略底部,仅用于处理错误。

When I use the $timeout, the modal closes before the route change, and we're gravy. 当我使用$ timeout时,模态在更改路线之前关闭,因此我们很注意。

Is there a better way to approach this problem? 有没有更好的方法来解决此问题?

You can use, $routeChangeStart which gets called on every navigation, or a route change, there you can close your modal. 您可以使用$routeChangeStart (在每次导航中被调用)或更改路线,在那里您可以关闭模​​态。

$rootScope.$on('$routeChangeStart', function() { })

Example: 例:

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

app.run(["$rootScope","$http","$location",
    function($rootScope,$http,$location){

    $rootScope.$on('$routeChangeStart', function() {
        $('.modal').modal('hide'); // hides all modals
        $('#login-modal').modal('hide'); // hides specific modal
        angular.element('.modal').hide(); // same as first, but a bit angular way
    })

}]) 

HEre is the documentation of the same. 这里是相同的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM