1

I am using HTML5 mode in AngularJS and I have a <base href="/some/base/path" /> defined in the <head> section of my HTML file.

What is the best way of reading this value in AngularJS? I understand that you can just read this HTML tag with jQuery, but something tells me this is not the most elegant way of doing it.

What I want to achieve

I would like to compose URL dynamically from controller. For instance, current page is http://localhost/myapp/some/custom/page/ where http://localhost/myapp is a base url. I want to build http://localhost/myapp/another/page url in angular controller by doing the following

baseUrl + `/another/page`
2
  • 3
    Why do you need to read it? What do you want to achieve? Commented Jan 3, 2016 at 9:01
  • 1
    This feels like an XY Problem. Angular has ways to handle your URL strings, URL parameters, etc.. Usually knowing the <base> isn't necessary to perform any angular logic, and as @JBNizet stated, you haven't mentioned what you want to achieve by reading this information. Commented Jan 3, 2016 at 10:39

1 Answer 1

1

AngularJS doesn't really have any functions for extracting attributes from tags. However, there are a workaround. But the pure javascript way I added at the bottom of the answer might be the best solution for you.

Let's say you change the base tag:

<base ng-controller="MyController" data-href="/some/base/path">

In your controller you can do the following to access data-href:

app.controller('MyController', function ($scope, $attrs) {
  console.log($attrs.href); // Prints '/some/base/path'
});

Or you can do it in pure javascript with:

var url = document.getElementsByTagName('base')[0].getAttribute('href');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I know that it's possible to access base via DOM, but I thought there is slightly more elegant solution out there for AngularJS

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.