从工厂更改控制器变量。 AngularJS

时间:2015-07-03 14:39:44

标签: javascript angularjs

我发现这个漂亮的方法可以在 angular 中捕获window.onbeforeunload事件。现在我想从它打开我的模态窗口,但我不知道怎么能这样做。

这是catch方法:

examinationApp.factory('beforeUnload', function($rootScope, $window) {
    // Events are broadcast outside the Scope Lifecycle
        $window.onbeforeunload = function(e) {
            var confirmation = {};
            var event = $rootScope.$broadcast('onBeforeUnload');
            if (event.defaultPrevented) {
                return confirmation.message;
            }
        };

        $window.onunload = function() {
            $rootScope.$broadcast('onUnload');
        };

        return {};
    })
    .run(function(beforeUnload) {
        // Must invoke the service at least once
    });
    examinationApp.controller("examinationCtrl", ['$scope', '$window', '$http', '$cookieStore', function ($scope, $window, $http, modalDialog) {
        $scope.$on('onBeforeUnload', function (e, confirmation) {
            confirmation.message = confirmation.message = "All data willl be lost.";
            e.preventDefault();
        });
        $scope.$on('onUnload', function (e) {
            console.log('leaving page'); // Use 'Preserve Log' option in Console
        });

在我的控制器中,我有一个变量"modalEndShow=false"。我希望在观看事件时切换它。

examinationApp.controller("examinationCtrl", ['$scope', '$window', '$http', '$cookieStore', function ($scope, $window, $http, modalDialog) {
modalEndShown=false;}]);

那我该怎么做呢?谢谢你的关注。

1 个答案:

答案 0 :(得分:0)

你可以通过这样做来制作模态弹出:

$scope.$on('onBeforeUnload', function (e, confirmation) {
    confirmation.message = confirmation.message = "All data willl be lost.";
    e.preventDefault();
    $scope.$apply(function() {
        $scope.modalEndShown = true;
    });
});