Search code examples
angularjshashangular-ui-routerhrefui-sref

AngularJS ui-router: ui-sref links aren't prepending the hash when filling in href values


My ui-router state provider is setup like so:

.state(
    'events', {
        url: '/events',
        templateUrl: ...,
        controller: ...
    })
.state(
    'events.listEvents', {
        url: '/list',
        templateUrl: ...,
        controller: ...
    })
.state(
    'events.eventDetails', {
        url: '/details',
        templateUrl: ...,
        controller: ...
    })


I start off in events.listEvents state, so my URL looks like this:

https://baseUrl.com/home#/events/list

and I have a link on that page like this:

<a ui-sref="events.eventDetails">event details</a>

When I just click the link normally, it works correctly and routes me to a page with the URL:

https://baseUrl.com/home#/events/details

but when I try to open that same link in a new tab (or when I right-click and copy the "href" link address), it's incorrect:

https://baseUrl.com/events/details



So the question is: Why is the ui-sref filling in the wrong href value? Why is it totally missing the # hash in the URLs it's generating? (And yes, I already tried enabling/disabled $locationProvider.html5mode and that didn't have any effect on this.)


Solution

  • I added this to my main app.js as a workaround:

    .run(['$state',
        function($state) {
            $state.originalHrefFunction = $state.href;
            $state.href = function href(stateOrName, params, options) {
                var result = $state.originalHrefFunction(stateOrName, params, options);
                if (result && result.slice(0, 1) === '/') {
                    return '#' + result;
                } else {
                    return result;
                }
            }
        }
    ])