0

i'm currently working on a asp.net mvc site in which we are using angularjs for model binding. i have a controller setup but i need to grab the id from the url to pass it to the service. my url looks like:

http://localhost/myapp/section/5

I need to grab the 5 out of the url, we are not using angular for routing, is there anyway to grab that through angular? Otherwise i could use .net to inject that into a global js variable and use angular to read the id from there.

I setup my angular controller as below:

    myModule.controller('SectionController', ['$scope', 'sectionRepository', '$routeParams', SectionController]);

function SectionController($scope, sectionRepository, $routeParams) {
    var vm = this;

    alert($routeParams.id);

the alert returns 'undefined', I'm assuming because I never setup the routes in angular, is there a way to do it without the setup of routes, as we don't want to use angular for routing.

1
  • maybe using $location.absUrl() and parsing the string Commented Apr 22, 2016 at 20:31

1 Answer 1

3

You can use the $location service to grab the URL. From there, just parse it.

function SectionController($location) {
    var url = $location.url();
    //regex is slow, you should use substring/slice instead
    //var regex = /(?:section\/)[0-9]+/;

    var id = url.substring(url.indexOf("section/") + "section/".length);
    alert(id);
}
Sign up to request clarification or add additional context in comments.

4 Comments

are you sure $location.url() will work if angular is not routing the application?
@SergioMarron According to the docs (docs.angularjs.org/api/ng/service/$location), it does not depend on routing. Changes in window.location are live and $location can see them.
I tried $location.path() and it returned an empty string. window.location.pathname worked.
@SergioMarron for me $location.url() did not work either, but after looking through the debugger, I saw there was is $location.absUrl() which worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.