如何在angularjs中重定向到新路由时显示确认弹出窗口?

a7qyws3x  于 2021-09-29  发布在  Java
关注(0)|答案(3)|浏览(363)

当我的angularjs应用程序中有路线更改时,我想显示一个确认弹出窗口(带有“是”和“否”按钮)。
我试过这样做。每次更改路线前都会调用此事件,但此函数不会限制用户前往其他路线,即使用户选择了“否”

$scope.$on('$locationChangeStart', function (event) {
      if (vm.counterObject.myList.length > 0) {
        var answer = confirm("Are you sure?")
        if (answer) {
          event.preventDefault();
        }
      }
    });

有没有关于我错在哪里的建议?

bqujaahr

bqujaahr1#

假设您希望显示部分页面中的模式,如下所示

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('OK')" class="btn btn-default">Success</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>

具有显示和隐藏模态的指令。

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
          scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

最后,当您单击一个按钮时,您希望重定向用户。

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
        if(btnClicked == "OK") {
        $window.location.href = '/index.html';
        }

    };
  });
dced5bon

dced5bon2#

终于在我的测试angularjs应用程序中实现了这一点。这是我从ben nadel的网站改编的方法。我决定在这里粘贴整个控制器
编辑:与上一种方法不同的是此函数中的ooo(操作顺序)。问题是我没有机会回答 $digest 当我们允许 $location.path() 通过。它仍在影响事件侦听器。 stopWatchingLocation() 取消该侦听器,但由于事件的关联,我们必须允许angular对其进行消化。
因此,从本质上讲,这使 proceedWithLocationChange 功能:
首先运行此命令: stopWatchingLocation(); 然后

$timeout(() => {$location.path( targetPath ).search( targetSearch ).hash( targetHash )},10);
}

它在我的环境中工作得很好

'use strict';
angular.module('myApp.view1', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {
    templateUrl: 'view1/view1.html',
    controller: 'View1Ctrl'
  });
}])

.controller('View1Ctrl', ['$scope', '$location', '$timeout', function($scope, $location, $timeout) {

$scope.currentLocation = $location.url();
$scope.myList =  [1,2,3]
$scope.$on(
    "$locationChangeSuccess",
    function handleLocationChangeSuccessEvent( event ) {
        $scope.currentLocation = $location.url();
    }
);

var startWatchingTimer = $timeout( startWatchingForLocationChanges, 0, false );
var stopWatchingLocation = null;

function handleLocationChangeStartEvent( event ) {
    event.preventDefault();
    var targetPath = $location.path();
    var targetSearch = $location.search();
    var targetHash = $location.hash();

    if ($scope.myList.length > 0) {
        if (confirm('Leave the page?')) {
            proceedWithLocationChange(targetPath, targetSearch, targetHash)
        }
    } else {
        proceedWithLocationChange(targetPath, targetSearch, targetHash)
    }
}

function proceedWithLocationChange(targetPath, targetSearch, targetHash) {
    stopWatchingLocation();
    $timeout(() => {$location.path( targetPath ).search( targetSearch ).hash( targetHash )},10);
}

function startWatchingForLocationChanges() {
    console.log("watching");
    stopWatchingLocation = $scope.$on( "$locationChangeStart", handleLocationChangeStartEvent );
}

}]);
aoyhnmkz

aoyhnmkz3#

在angularjs中,您可以使用run函数来监听 $stateChangeStart 事件并采取行动。正如其名称所指出的,它发生在转换发生之前,您可以取消或重定向到其他位置。这也可以在组件级别完成。

angular.module('MyApp').run(canRedirect);
/**@ngInject */
function canRedirect($rootScope, $window, SomeService) {
    const stateChangeStart = $rootScope.$on('$stateChangeStart', (event) => {
        // add your logic and take action
        if (SomeService.hasPermission()) {
            event.preventDefault();
            $window.location = '/path/to/redirect';
        }
    });
    $rootScope.$on('$destroy', canRedirect);
}

相关问题