Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to parse requested URL in AngularJS

I have a URL like:

http://www.something.com/project/edit/987654321

What's the best way to parse the 987654321 part of the URL using AngularJS? Are there any helper functions within Angular? (I'd prefer to not use jQuery)

If I understand it correctly, the routing functions within AngularJS won't work unless you use a # within the URL or enabled HTML5 mode.

We need to parse this URL when the page is first loaded.

like image 944
Ender2050 Avatar asked Feb 20 '14 21:02

Ender2050


3 Answers

I'll answer the question based on the title because I landed here looking for a way to parse a url as well. Here's the answer I found on a fiddler page.

var parser = document.createElement('a');
parser.href = "http://www.example.com";
//At this point it's parsed and all the info is on the parser object
console.log(parser.protocol);
console.log(parser.hash);
console.log(parser.hostname);
console.log(parser.port);
console.log(parser.pathname);
console.log(parser.search);

[Update]
I just noticed there's a URL class.

var parsedURL = new URL('http://www.example.com');
console.log(parsedURL.hash);
console.log(parsedURL.protocol);
console.log(parsedURL.host);
//etc
like image 141
Jerinaw Avatar answered Nov 04 '22 01:11

Jerinaw


You can use the $location service's $location#path() function:

# given: url = http://www.something.com/project/edit/987654321
$location.path().split('/').pop();

However, it sounds like you have a routing issue. Check out the Angular Tutorial on Routing, which shows how to correctly use $routeProvider routes in your app.js configuration. From the tutorial:

phonecatApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
       when('/phones/:phoneId', {
        templateUrl: 'partials/phone-detail.html',
        controller: 'PhoneDetailCtrl'
      })
      .otherwise( ...)  //omitting remainder of cut/paste

So your app.js would have a route definition like:

ender2050App.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/project/edit/:id', {
        templateUrl: 'partials/editor.html',
        controller: 'EditorCtrl'
      })

And your controller file (i.e., controllers.js) would have the EditorCtrl that injects the $routeParams service to access the id variable.

If you need a more customized parsing option, check out the $parse service.

like image 37
JJ Zabkar Avatar answered Nov 04 '22 01:11

JJ Zabkar


Both the question AND the answer don't respect the title. I landed here trying to search how to parse ANY url in angular. This question is about parsing the requested url. What if I want to parse http://www.google.com ??

Edited it.

like image 21
Cyril CHAPON Avatar answered Nov 04 '22 03:11

Cyril CHAPON