Ionic override all BACK button behaviour for specific controller

前端 未结 6 1092
醉梦人生
醉梦人生 2020-11-29 02:51

I want to be able to override the BACK button on the navigation bar, and the hardware button.

I want this override to be for one specific controller, but not for the

6条回答
  •  再見小時候
    2020-11-29 03:34

    Took the feedback from @raven.zuo and made some amends to un-register the state change event.

    (function () {
        'use strict';
    
        angular
            .module('appName')
            .service('customBackButtonService', customBackButtonService);
    
        customBackButtonService.$inject = ['$rootScope', '$ionicPlatform'];
        function customBackButtonService($rootScope, $ionicPlatform) {
    
            var service = {
                setup: setup
            };
    
            return service;
    
            ////////////////
    
            function setup(customBackFunction) {
                // override soft back
                // framework calls $rootScope.$ionicGoBack when soft back button is pressed
                $rootScope.oldSoftBack = $rootScope.$ionicGoBack;
                $rootScope.$ionicGoBack = function () {
                    customBackFunction();
                };
                var deregisterSoftBack = function () {
                    $rootScope.$ionicGoBack = $rootScope.oldSoftBack;
                };
    
                // override hard back
                // registerBackButtonAction() returns a function which can be used to deregister it
                var deregisterHardBack = $ionicPlatform.registerBackButtonAction(
                    customBackFunction, 101
                );
    
                // cancel custom back behaviour
                var backStateChangeWatcher = $rootScope.$on('$stateChangeStart', function () {
                    if($rootScope.oldSoftBack){
                        deregisterHardBack();
                        deregisterSoftBack();
    
                        // Un-register watcher
                        backStateChangeWatcher();
                    }
                });
            }
        }
    })();
    
    //Called via:
    
        customBackButtonService.setup(function () {
            console.log('custom back');
        });
    

提交回复
热议问题