2

Given the template for our url /foo the HTML contains the following:

<a href="#bar" ng-click="myfunc()">Hello</a>

My expectation is that this would direct me to /foo#bar. Instead, it leads me to /foo#/bar, which is a problem because I need to use the value bar. Right now I am forcibly removing the slash to get the value bar, but it's awfully hacky.

I am aware this is due to $location and angularjs's routing mechanism. The following link gives a solution which would normally clear this up: AngularJS 1.1.5 - automatically adding hash tag to URLs.

However, enabling html5mode screws up the rest of our links, as it seems to assume we're using a single-page app, while we really aren't. In fact, we aren't even doing routing through angularjs.

All I'm looking for is a way to remove the slash from the location's hash. Is there a simpler solution to this issue?

Note: Bar may be the name of a tab within a page, or it may be a div you can scroll to. I'd prefer to keep it as a simple "#" syntax for clarity to others working on the project.

Community
  • 1
  • 1
limasxgoesto0
  • 4,555
  • 8
  • 31
  • 38

1 Answers1

1

Yes, angular does assume that you're using a SPA, because angular is a framework for SPAs. As such, relative links are always handled as if they're going to a different ng-view, hence the added /.

I don't know if there is a way to turn off the angular router, but an alternative is $location.hash() and $anchorScroll().

I would suggest the best way to do this is to put a function in scope (rootScope if you use anchors a lot) something like the following:

app.run( function($rootScope, $location, $anchorScroll){ 
  $rootScope.scrollTo = function(id){
    $location.hash(id);
    $anchorScroll();
  }
});

Then your html would look like this:

<a ng-click="anchorScroll('bar')">Hello</a>
Ed_
  • 18,798
  • 8
  • 45
  • 71
  • That feels a little over the top to get a relatively small piece of functionality working. Plus, the bar value may be a tab (I'll add this to the original question) and there may be multiple functions to use with ng-click. – limasxgoesto0 Mar 12 '14 at 18:31
  • Though it seems a small part of your own app, `$location` and its manipulation is a large part of the angularJS framework. You have chosen to use it differently than it is designed, so there is a lot to 'undo'. I'm not sure what you mean about the tabs - in the angular world, a tabbed view should be handled by a directive. If you want to try something more drastic - try reading up on whether it's possible to disable the `$location` service. [This question](http://stackoverflow.com/questions/18611214/turn-off-url-manipulation-in-angularjs) is along the right lines. – Ed_ Mar 12 '14 at 18:45