5

I'm using angular to develop an application. I'm developing off my local file system, on Windows. However, when I enable angular-route.js, whenever I hit index.html with my browser, it instead goes to index.html#/C:/.

My route definition is:

myApp.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/', {templateUrl: 'home.html', controller: 'HomeCtrl'});
}

I think this causes the site to break, because /C:/ doesn't match any angular routes. What's going wrong? How do I fix this?

Chris B.
  • 85,731
  • 25
  • 98
  • 139

2 Answers2

7

For routing & ajax (& more) to work properly, run a local development server; avoid use of file:// for development, since browsers have different rules for it.

Tools like yeoman + generator-angular will automatically set up a gruntfile with a server task, which will run a node-connect server to locally serve your files.

You can do this with

  • python: (3)python -m http.server 8001 (replace http.server with SimpleHttpServer in 2)
  • node.js + connect
  • ruby + rack
  • From the angularjs tutorial (number 5 under "working with the code") - "You need an http server running on your system, but if you don't already have one already installed, you can use node to run scripts\web-server.js, a simple bundled http server."

Response from comments: For phonegap, use the phonegap tools. It does exactly what I said, it runs a local server.

Community
  • 1
  • 1
forivall
  • 9,504
  • 2
  • 33
  • 58
  • I believe the phonegap tools are designed to compile and package phonegap applications locally or remotely, and to run the resulting builds in simulators. Not to serve files locally. – Chris B. Oct 21 '13 at 20:23
  • https://github.com/phonegap/phonegap-cli/blob/e6b76e1627713c02c5fa02ead0cc06c63f9b7749/lib/phonegap/app.js#L27 - "Creates a local server to serve up the project. The intended receiver is the PhoneGap App but any browser can consume the content." – forivall Oct 21 '13 at 20:25
  • 1
    Also, edited: the angular tutorial itself tells you to run an http server. There's probably something that says that you can't run it off of `file://`, but it's not worth finding, because I know it's true; you can't run it off of `file://`; angular can't parse the windows path as a root directory because it's not a url it would ever encounter in the wild. – forivall Oct 21 '13 at 20:34
3

This will work.

angular.module('MainModule', []).config(function($locationProvider, $routeProvider) {
    $locationProvider.hashPrefix("!");
    $locationProvider.html5Mode(false);
    $routeProvider.when('/', {template: './js/templates/home.html', controller:HelloWorldCtrl});
    $routeProvider.when('/other', {template: './js/templates/other.html'});
});

In index HTML you need to specify templates:

<script type="text/ng-template" src="./js/templates/home.html"></script>
<script type="text/ng-template" src="./js/templates/other.html"></script>
Brian McAuliffe
  • 2,099
  • 1
  • 16
  • 13