David Slavík
David Slavík

Reputation: 1192

AngularJS: how to change location path in routeChangeStart event?

In my application I'm using some query string parameters to resolve links for preselecting some data. But I would like to hide these parameters for users. For example, where I'm using a route like localhost/myapp#/settings?key=dataGrid&value=10, I want to clear these parameters and show user a route like localhost/myapp#/settings.

I tried something like this:

angular.module('myApp')
.run(['$rootScope', '$sce', '$location', '$route',
    function($rootScope, $sce, $location, $route) {
        $rootScope.$on('$routeChangeStart', function(event, next, current) {
            if ($location.url().indexOf('?key=')) {
                var newLocationPath = $location.url().substring(
                    0, $location.url().indexOf('?key='));
                $location.path(newLocationPath).search('');
            }
        });
    }]);

But it does not do anything. On StackOverflow I found something about using $rootScope.$Apply, but if it try it, I get this error: [$rootScope:inprog] $digest already in progress.

Upvotes: 1

Views: 9073

Answers (1)

Chofoteddy
Chofoteddy

Reputation: 757

Try: $locationChangeStart to handle page changes. Your code would be as follows:

$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl){
    $rootScope.target = $location.search()['key']; // (equivalent) key = GET[key]
    // $rootScope.target = $location.search().key; // Other solution
});

To set a parameter to the url from a controller (without use of a link), the code is as follows:

myApp.controller('MyCtrl',function($scope, $location) {

    // setParam('key', 'dataGrid')
    $scope.setParam = function(param, value) {
        $location.search(param, value); // domain.com/#/page?key=dataGrid
    };

});

Live example: http://jsfiddle.net/Chofoteddy/3wFeR/

That said, your code would be as follows:

$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl){
    var param = $location.search()['key'];
    $location.path(param).search(''); // Change url and clean params
});

More info: $rootScope.$on("$locationChangeStart")

Upvotes: 4

Related Questions