事件没有等待$ mdDialog确认

时间:2017-07-11 03:29:53

标签: javascript angularjs scope angularjs-scope angular-material

我想在$ locationchangestart中调用$ mdDialog的行为时就像confirm()一样。 在恢复位置更改之前,$ mdDialog不会等待用户输入。

$rootScope.showConfirm = function (ev) {
        // Appending dialog to document.body to cover sidenav in docs app
        var confirm = $mdDialog.confirm()
            .title('Tem certeza que deseja sair?')
            .textContent('Informações não salvas serão perdidas"')
            .targetEvent(ev)
            .ok('Sim')
            .cancel('Não');

        $mdDialog.show(confirm).then(function () {
            $rootScope.status = true;
        }, function () {
            $rootScope.status = false;
        });
    };


 $rootScope.$on("$locationChangeStart", function (event, next, current) {
        $rootScope.showConfirm(event);

        if($rootScope.status == false){
            event.preventDefault();
        }
    });

2 个答案:

答案 0 :(得分:0)

尝试按如下方式修改钩子$locationChangeStart并查看它是否有效:

$rootScope.$on("$locationChangeStart", function (event, next, current) {
        if(!$rootScope.showConfirm(event)) {
            event.preventDefault();
        }
});

修改showConfirm以根据用户响应返回true / false,如下所示:

$mdDialog.show(confirm).then(function () {
  return true;
}, function () {
  return false;
});

有一个类似的问题已经回答here。希望也有帮助。

答案 1 :(得分:0)

此实现不是最好的,并且具有不好的代码味道,但确实可以。我仍在寻找解决该问题的更好方法,如果确实遇到问题,请告诉我。

var isLeaving = false;

$scope.$on("$routeChangeStart", function (event, next, current) {
    if ($scope.form.$dirty && !isLeaving) {
        event.preventDefault();
        var dialog = $mdDialog.confirm()
            .parent(angular.element(document.body))
            .clickOutsideToClose(false)
            .title('Exit Form')
            .textContent('Are you sure you want to exit?')
            .ariaLabel('Exit Form')
            .ok('Yes')
            .cancel('No');

        $mdDialog.show(dialog).then(function () {
            //do something here...
            isLeaving = true;
            $location.path(next.$$route.originalPath)
        }, function () {
            //do something here...
            isLeaving = false;
        });
    }
});