Turn off URL manipulation in AngularJS

不问归期 提交于 2019-11-26 19:59:45
greg.kindel

Not sure of the side effects of this, but it gets the job done. Note that it will disable all location manipulation from the angular app, even if intended.

angular.module('sample', [])
    .config( ['$provide', function ($provide){
        $provide.decorator('$browser', ['$delegate', function ($delegate) {
            $delegate.onUrlChange = function () {};
            $delegate.url = function () { return ""};
            return $delegate;
        }]);
    }]);

ES6 variant:

angular.module('sample', [])
    .config(["$provide", $provide => {
        $provide.decorator("$browser", ["$delegate", $delegate => {
            $delegate.onUrlChange = () => { };
            $delegate.url = () => "";

            return $delegate;
        }]);
    }]);

Tested in Chrome 30, IE9, IE10.
Inspired by https://stackoverflow.com/a/16678065/369724

I use a local copy of angular.js. Search for

$browser.onUrlChange(function(newUrl, newState) {

and

$rootScope.$watch(function $locationWatch() {

comment out the corresponding lines and angularjs will stop watch for location url changes.

If I recall correctly, Angular's routing is not obligatory, but then you must take care of reloading controllers, views, etc.

Thank @greg.kindel 's answer, you help me find a solution to solve anchor problem. This code let AngularJS app IGNORE some hash pattern, keep it working like browser default. I don't need enable html5Mode, and ngRoute still working. :)

app.config(['$provide', function ($provide) {
    $provide.decorator('$browser', ['$delegate', '$window', function ($delegate, $window) {
        // normal anchors
        let ignoredPattern = /^#[a-zA-Z0-9].*/;
        let originalOnUrlChange = $delegate.onUrlChange;
        $delegate.onUrlChange = function (newUrl, newState) {
            if (ignoredPattern.test($window.location.hash)) return;
            originalOnUrlChange.apply($delegate, arguments);
        };
        let originalUrl = $delegate.url;
        $delegate.url = function (url, replace, state) {
            if (ignoredPattern.test($window.location.hash)) return $window.location.href;
            return originalUrl.apply($delegate, arguments);
        };
        return $delegate;
    }]);
}]);

Tested in Chrome 69, Firefox 62

AngularJS 1.7.4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!