javascript - Angular JS 应用程序 ng-href 兼容 Web 和 Phonegap/Cordova

标签 javascript angularjs cordova

我们有一个 Web 和 Phonegap 应用程序,它在 Web 中使用 Angular HTML5 模式,并且由于 Cordova/Phonegaps 限制,在移动应用程序中使用 HashBang 模式。直到不久之后,我们才在所有 ng-href 前面加上 #!我们很高兴转向移动和网络。解析时,Angular 会自动将 href 属性中的 hashbang url 转换为 html5 url。

我们更新到 Angular 1.5 并注意到奇怪的行为:Hashbang 链接可以在整个页面重新加载时工作(例如打开一个新选项卡),但在单击它们并在同一页面中打开它们时则不行。 Angular 只会再次打开当前页面并附加哈希值,而不对其进行处理。

我搜索了changelog ,但没有找到有关此问题的 ng-href 或 $location 更改的任何提示。我如何设计我的链接以便它们在phonegap和网络中工作?

最佳答案

我找到了解决方案,但我希望有更好的解决方案。我创建了一个指令来覆盖 ng-href 并根据配置的平台替换链接。这样,在 Cordova 中,所有链接都是 hashbang 链接,而在网络上,所有链接都是普通链接。

在代码示例中,window.isPhonegapApp被设置为配置值来指示状态。将 myApp 替换为您的应用名称。

// directive that replaces hashbangs according to app type
angular.module('myApp')
.directive('ngHref', function($interpolate) {
return {
    priority: 99, // it needs to run after the attributes are interpolated
    link: function(scope, element, attr) {
        var attrName = 'href',
            name = 'href';

        if (attrName === 'href' &&
            toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
            name = 'xlinkHref';
            attr.$attr[name] = 'xlink:href';
        }

        var normalized = attr.$normalize('ng-href');
        attr.$observe(normalized, function(value) {
            if (!value) {
                if (attrName === 'href') {
                    attr.$set(name, null);
                }
                return;
            }


            if(window.isPhonegapApp) {
                if(!value.startsWith('#!')) {
                    value = '#!' + value;
                }
            } else {
                if(value.startsWith('#!')) {
                    value = value.replace("#!", '');
                }
            }
            attr.$set(name, value);
        });
    }
};
    // kick out the old ng-href directive and overwrite it with our directive
}).decorator('ngHrefDirective', function ngClickDecorator( $delegate) {

    var filteredDelegates =  _.filter($delegate, function($directive) {
        // replace with your app name
        return $directive.$$moduleName == 'myApp';
    });

    return filteredDelegates;
});

关于javascript - Angular JS 应用程序 ng-href 兼容 Web 和 Phonegap/Cordova,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36353551/

相关文章:

$.each 内的 javascript 变量新作用域

javascript - 如何与重叠形状的 d3.js 鼠标事件交互?

angularjs - 未知提供商 : $state

android - Appium/wdio - 无法关闭 Android 上的位置权限警报

javascript - 需要播放/停止按钮 javascript 帮助

javascript - 根据 1 个属性过滤对象数组,不限于文本开头

javascript - 在给定的时间范围 javascript 后清除每个通知

javascript - AngularJS 发布到 Controller 并重定向到另一个页面

javascript - 无法读取输入| Angularfire + Firebase

angularjs - Cordova 文件传输到 Node 服务器