AngularJS routing not working properly in PhoneGap

angular-routingangularjscordova

I have been beating my head against the wall trying to figure out why angularJS routing won't work in phonegap for me. I have all the files setup correctly and i don't receive any errors. I'm trying to change the url using the $location.url service directly from angular. So when you tap on a div the controller will have $location.url("profile") for example and nothing will happen. I tried the solution found in this stackoverflow but that's not working for me. Am I doing something wrong, or is there a better way to be approaching this? Following is the routing I have setup

var app = angular.module("App", ["hmTouchevents"])
.config(function($routeProvider) {

$routeProvider
    .when("/index.html", {
        templateUrl: "/views/login.html",
        controller: "loginCtlr"
    })
    .when("/landing", {
        templateUrl: "/views/landing.html",
        controller: "landingCtlr"
    })
    .when("/single-view/:id", {
        templateUrl: "/views/single-view.html",
        controller: "singleViewCtlr"
    })
    .when("/restaurant", {
        templateUrl: "/views/restaurant-info.html",
        controller: "restaurantCtlr"
    })
    .when("/profile/:id", {
        templateUrl: "/views/profile.html",
        controller: "profileCtlr"
    })
    .when("/lists/:list", {
        templateUrl: "/views/lists.html",
        controller: "listsCtlr"
    })
    .when("/follow/:type", {
        templateUrl: "/views/follow.html",
        controller: "followCtlr"
    });

});

A sample controller would be:

app.controller("listsCtlr", ["$scope", "$location", function($scope, $location){

$scope.goTo("profile");

}]);

As always any help is much appreciated.

Best Answer

I had a problem similar to this tonight. The core issue here is that PhoneGap doesn't have a web server built in. If you're developing locally, you probably are using a web server, so you can do something like: http://localhost/#/profile and the routing will work.

However, PhoneGap loads your code with a file:// URL, not http://. If you do $location.url("profile") you're replacing the entire URL with just file://profile, which doesn't exist. Same thing if you use a link like this: <a href="/#/profile">My Profile</a>

The solution is to somehow get your links to point to the right place. If you're using $location.url() you can prefix it with your file path: $location.url( window.location + "#/profile" )

If you're just making a link, you should be able to get away with taking off the leading slash to make it a relative URL: <a href="/#/profile">My Profile</a> becomes <a href="#/profile">My Profile</a>