Chirag Agrawal Chirag Agrawal - 4 months ago 16
AngularJS Question

$location.path redirects to wrong location

This function is called when a button is clicked on my web page.

$scope.go=function(takenAt){
var path = '/oneMinuteMetric/loadCapturedMetrics?'+'&timestamp=' + takenAt + '&tagName='+ $stateParams.tagName;
console.log(path); //first
$location.path(path);
console.log($location.path()); //second
};


But strangely when my page is redirected, the location is completely wrong.

The first
console.log
prints
/oneMinuteMetric/loadCapturedMetrics?&timestamp=1467976859092&tagName=TestTag


and the second
console.log
also prints
/oneMinuteMetric/loadCapturedMetrics?&timestamp=1467976859092&tagName=TestTag


whereas in my browser window the path is
/oneMinuteMetric/loadCapturedMetrics?tagName=TestTag&timestamp=1468143868308%2F%3FtagName%3DTestTag


"
%2F%3FtagName%3DTestTag
" get appended on its own and then my request is rejected as bad request by the server. We have used this method for redirecting at several places but strangely it does not work here. Why?

PS: The location of my web page is
/oneMinuteMetric/tagHistory?tagName=TestTag
. This where the button is clicked and the given function is executed

Answer

Use $location.search() to add query parameters.

$location.path("/oneMinuteMetric/loadCapturedMetrics");
$location.search({'timestamp' : tokenAt, 'tagName' : $stateParams.tagName });

When you pass an array to $location.search() it will override the existing query parameter component.

In your case, the query parameter "%2F%3FtagName%3DTestTag" still exists from current url because $location.path() will only update the path and won't modify/override query parameter component.

Comments