Reputation: 4203
I have an annoying issue I'm not sure there's a solution to; We run html5mode in production, but not in development. The reason is that this is difficult to setup on spring-boot's embedded tomcat. We are coding our html anchors like this:
<a href="/route">Route</a>
which of course breaks when not in html5mode where angular will expect the href to be "#/route"
instead - which is a real pain. The only way we've found to avoid this problem, is to code links like this:
<a href="#" ng-click="goto('/route')">Route</a>
and have a global function in i.e. $rootScope:
$scope.goto = function (route) {
$location.path(route);
}
But this just seems wrong. I had hoped that using ng-href insted of href on the anchor would sort this out (perhaps detecting if we are in html5mode or not, and auto-add the hash to the url so that we do not need to refactor the entire app if we switch modes), but it doesn't.
Is there no way of using anchors WITHOUT explicitly stating hash urls?
Upvotes: 2
Views: 481
Reputation: 4203
Ok, I still believe this to be a design flaw in angular, and that this particular fix should exist within angular itself.
This directive is matched directly on the 'href' attribute. I've not done any testing on how this affects performance, but it does perform rewrites on internal url's only.
angular.module(_DIRECTIVES_).directive('href', ['$location', function ($location) {
'use strict';
return {
restrict: 'A',
scope: {
href: '@'
},
link: function (scope, element, attrs) {
// Check if we need to rewrite the href
var currentBase = $location.$$protocol + '://' + $location.$$host;
var newBase = element[0].href;
if (element[0].nodeName == 'A' && newBase.indexOf(currentBase) == 0 && !$location.$$html5) {
// Perform the href AFTER angular has done it's thing. Otherwise angular will rewrite back to the original
scope.$watch('href', function () {
// This function may be run several times. Make sure the rewrite only happens once.
if (scope.href.indexOf('#!') !== 0) {
scope.href = '#!' + scope.href;
element.attr('href', scope.href);
}
});
}
}
};
}]);
I hope this will help anybody else in the same predicament as me. Also hope that angular will fix this in the future.
Upvotes: 3