AngularJS and PhoneGap: $location.path causes subsequent tempateUrl lookup to fail

天涯浪子 提交于 2019-11-29 02:00:16

For future reference, this is how I managed to solve the problem:

  1. AngularJS currently does not seem to support html5mode(true) inside a Cordova application because of the insecurl problem I reported. What I had to do is add

    var h5m = (typeof html5Mode !== 'undefined') ? html5Mode : true;
    $locationProvider.html5Mode(h5m);
    

    which gives me the possibility to explicitly set html5Mode in the PhoneGap index.html with a global variable:

    <script>
      var html5Mode = false;
    </script>
    
  2. So now $location.path('/login') as well as redirectTo: 'login' works, but links in html files, don't. To get those working in PhoneGap, with html5Mode disabled, I had to add #/ in front of every link, e.g. <a href="#/login">login</a>.

  3. That makes PhoneGap work, but breaks the web page which uses History API with html5Mode(true). The last piece of the puzzle was to add <base href="/"/> to the web page's index.html (and leave it out of the index.html of the PhoneGap project.) So now even though I have a link that says #/login in the web page, I get to the url http://example.com/login and don't see any hashes in the address bar.

**

So in the end I have History API working in my web page and History API disabled in the PhoneGap project (where there really is no need for History API as there is no address bar). The only downside is the extra #/ I have to put in each template html file, but that is a minor annoyance compared to the ability to use all of the same html and javascript files for both web and mobile.

I had this same problem as well. I managed to fix it by skipping the leading slash in the route config:

 $routeProvider
        // route for the foo page
        .when('/foo', {
            templateUrl: 'foo.html', //previously: '/foo.html'
            controller: 'fooController'
        }) //etc.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!