切换到html5mode时,角锚会中断

时间:2014-02-28 16:57:39

标签: javascript html angularjs

我有一个恼人的问题我不确定是否有解决方案; 我们在生产中运行html5mode,但不在开发中。原因是在spring-boot的嵌入式tomcat上很难设置。我们正在编写像这样的html锚:

<a href="/route">Route</a>

当不在html5mode中时会发生中断,其中angular会指望href为"#/route" - 这是一个真正的痛苦。我们发现避免这个问题的唯一方法是编码这样的链接:

<a href="#" ng-click="goto('/route')">Route</a>

并且在$ rootScope中具有全局函数:

$scope.goto = function (route) {
    $location.path(route);
}

但这似乎错了。我曾希望在锚点上使用ng-href输入href会对此进行排序(可能会检测我们是否在html5mode中,并自动将哈希添加到url中,这样我们就不需要重构整个应用程序了我们切换模式),但事实并非如此。

没有办法在没有明确说明哈希网址的情况下使用锚点吗?

1 个答案:

答案 0 :(得分:3)

好吧,我仍然认为这是一个有角度的设计缺陷,并且这个特殊的修复应该存在于角度本身内。

此指令直接与&#; href&#39;匹配。属性。我没有对这会如何影响性能进行任何测试,但它确实只对内部网址执行了重写。

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);
                    }
                });
            }
        }
    };
}]);

我希望这能帮助处于同样困境的其他人。也希望angular能在将来解决这个问题。