Ionic override all BACK button behaviour for specific controller

前端 未结 6 1088
醉梦人生
醉梦人生 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:27

    I took Richard's suggestion and put it into a service to make it more reusable.

    The Controller

    angular.module('MainApp').controller('MyController', ['backButtonOverride'], function (backButtonOverride) {
        // override back button for this controller
        backButtonOverride.setup($scope, function() {
            console.log("custom back");
        });
    }
    

    The Service

    angular.module('MainApp.services', []).factory('backButtonOverride', function ($rootScope, $ionicPlatform) {
        var results = {};
    
        function _setup($scope, customBackFunction) {
            // override soft back
            // framework calls $rootScope.$ionicGoBack when soft back button is pressed
            var oldSoftBack = $rootScope.$ionicGoBack;
            $rootScope.$ionicGoBack = function() {
                customBackFunction();
            };
            var deregisterSoftBack = function() {
                $rootScope.$ionicGoBack = 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
            $scope.$on('$destroy', function() {
                deregisterHardBack();
                deregisterSoftBack();
            });
        }
    
        results.setup = _setup;
        return results;
    });
    

提交回复
热议问题