2016-04-01 6 views
1

WebでAngular HTML5モードを使用し、Cordova/Phonegapsの制限により、モバイルアプリ向けのHashBangモードがあります。まもなく私たちはすべてのng-hrefに#をつけました。私たちはモバイルとウェブのために行くことができました。 Angularは、解決時にhref属性のhashbang URLを自動的にhtml5 urlに変換します。WebとPhonegap/Cordova用Angular JS App ng-href互換

Angular 1.5に更新され、奇妙な動作に気付きました:ハッシュバンリンクはフルページのリロード(新しいタブを開くなど)では動作しますが、同じページで開くと動作しません。 Angularは、現在のページをもう一度開き、処理せずにハッシュを追加します。

changelogを検索しましたが、この問題に関するng-hrefまたは$ locationの変更に関するヒントは見つかりませんでした。私はリンクをデザインして電話機とウェブで動作させることができますか?

答えて

0

解決策が見つかりましたが、より良い解決策が見つかるはずです。 ng-hrefを上書きし、設定されたプラットフォームに従ってリンクを置き換える指令を作成しました。この方法では、コードバーではすべてのリンクがハッシュバングリンクであり、ウェブ上ではすべてのリンクが通常のリンクです。

コードサンプルでは、​​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; 
}); 
関連する問題