Unable to get current route. $ location.path () returns empty.

I am currently in /addDoc , and I need the current route I am on. 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 do not want to hard code all the routes. What am I doing wrong?

+6
source share
3 answers
Location service

$ is responsible for parsing the URL in the address bar of the browser and makes the URL available to your APP.

Since you use regular URLs and search segments, you need to set the $ locationProvider html5Mode parameter to true.

$ locationProvider will use hashbang as its default mode.

If you do not set html5Mode to true, you will get an empty string when trying to get the url.

Then use the $ location function to retrieve the url after installing html5Mode.

And write your own rule to handle the path.

Suppose your full URL is as follows: 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 helps you.

+20
source

Try this also, this is native code in JS. It worked for me. But if you need to parse a long URL with many subpages, you need to change the code a bit.

 var path = "/" + window.location.pathname.split('/')[1]; console.log(path ); 
+1
source

Use $location.absUrl() .... Full URL Looks like: http: // localhost: 6292 / Example / URLName

0
source

Source: https://habr.com/ru/post/979260/


All Articles