繁体   English   中英

Angular JS App ng-href兼容Web和Phonegap / Cordova

[英]Angular JS App ng-href compatible for Web and Phonegap / Cordova

我们有一个Web和Phonegap应用程序,它在Web中使用Angular HTML5模式,并且由于Cordova / Phonegaps限制,移动应用程序的HashBang模式。 直到不久,我们只用#来为我们所有的ng-href做好了前缀! 我们很高兴去移动和网络。 解决时,Angular会自动将href属性中的hashbang网址转换为html5网址。

我们更新到Angular 1.5并注意到奇怪的行为:Hashbang链接可以在整页重新加载(例如打开一个新的Tab),但不是在点击它们并在同一页面中打开它们时。 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;
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM