Angular ng-view/routing not working in PhoneGap

After searching through several questions and forums, I’ve finally got it working reliably. This is what it took me to get it running from a clean PhoneGap project.

index.html

<!DOCTYPE html>
<html ng-app="App">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
    <link rel="stylesheet" type="text/css" href="https://stackoverflow.com/questions/15105910/css/index.css" />
    <title>Hello World</title>
</head>
<body>

    <a href="#/">Main View</a>
    <a href="#/view">New View</a>

    <div ng-view></div>

    <!-- Libs -->
    <script type="text/javascript" src="lib/cordova-2.5.0.js"></script>
    <script type="text/javascript" src="lib/angular-1.0.5.js"></script>

    <!-- App -->
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript" src="js/routers.js"></script>
    <script type="text/javascript" src="js/controllers.js"></script>
    <script type="text/javascript">
        app.initialize();
    </script>
</body>
</html>

Note the <html ng-app="App"> tag. The app won’t load without a value for the directive, so make sure you include one.

index.js

var app = {
    initialize: function() {
        this.bindEvents();
    },
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, true);
    },

    onDeviceReady: function() {
        angular.element(document).ready(function() {
            angular.bootstrap(document);
        });
    },
};

In this file, we’re manually bootstrapping Angular when PhoneGap fires the 'ondeviceready' event.

routers.js

angular.module('App', [])
.config(function ($compileProvider){
    $compileProvider.urlSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel):/);
})
.config(function ($routeProvider) {

    $routeProvider
    .when("https://stackoverflow.com/", {
        controller: TestCtrl,
        templateUrl: 'partials/main.html'
    })
    .when('/view', {
        controller: ViewCtrl,
        templateUrl: 'partials/view.html'
    });
});

This file has two important things in it. First, we’re creating the module with the same name we used before in <html np-app="App">. Second, we need to configure the router to whitelist
file URIs. I personally didn’t need this, but several people seem to have encountered the issue, so I included it.

controllers.js

function TestCtrl($scope) {
    $scope.status = "It works!";
}

function ViewCtrl($scope) {
    $scope.status = "Also totally works!";
}

Finally, just some basic controllers.

I’ve created a github repo with all of this here.

Hope this helps someone else.

Leave a Comment