Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get current route. $location.path() returns empty.

Tags:

angularjs

I am currently at /addDoc, and I want current route I am at. Here is my controller:

app.controller('DocRegistrationController',[ '$http', '$scope', '$upload', '$location', function($http, $scope, $upload, $location){
$scope.validation=function(){
   alert($location.path());
}
    }

However it returns empty. I dont want to hardcode all the routes. What am I doing wrong?

like image 686
Pravin Avatar asked Dec 08 '14 06:12

Pravin


1 Answers

$location service respond for parsing url in browser address bar and make the URL available to your APP.

Because you're using regular URL path and search segments, you have to set $locationProvider html5Mode to true.

$locationProvider will use hashbang as default mode.

If you don't set html5Mode to true, you will get empty string when you try to fetch url path.

Then use $location service to fetch the url path after set html5Mode.

And write your own rule to process the path.

Assume that your Full URL looks like: http://example.com/person/show/321

Main.js

angular.module("MyAPP",[],function($locationProvider){
    $locationProvider.html5Mode(true);
});

function MainController($location){
    var pId = $location.path().split("/")[3]||"Unknown";    //path will be /person/show/321/, and array looks like: ["","person","show","321",""]
    console.log(pId);
}

index.html

<!DOCTYPE html>
<html lang="en" ng-app="MyAPP">
    <head>
        <meta charset="utf-8">
        <title>Angular test</title>
    </head>
    <body ng-controller="MainController">
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
        <script src="js/main.js"></script>
    </body>
</html>

Hope this is helpful for you.

like image 159
Ataboy Josef Avatar answered Nov 14 '22 12:11

Ataboy Josef