vzhen vzhen - 1 year ago 77
AngularJS Question

How to config routeProvider and locationProvider in angularJS?

I want to active html5Mode in angularJS but I don't know why it not working. Any wrong with my codes?

.config(function($locationProvider, $routeProvider) {
$routeProvider.when('/', {
templateUrl: 'partials/home.html',
controller: HomeCtrl

$routeProvider.when('/tags/:tagId', {
templateUrl: 'partials/result.html',
controller: TagResultCtrl
//$routeProvider.otherwise({redirectTo: '/home', controller: HomeCtrl});

in html

<a href="tags/{{tag.id}}"><img data-ng-src="{{tag.imageUrl}}"></a>

Answer Source

The only issue I see are relative links and templates not being properly loaded because of this.

from the docs regarding HTML5 mode

Relative links

Be sure to check all relative links, images, scripts etc. You must either specify the url base in the head of your main html file (<base href="/my-base">) or you must use absolute urls (starting with /) everywhere because relative urls will be resolved to absolute urls using the initial absolute url of the document, which is often different from the root of the application.

In your case you can add a forward slash / in href attributes ($location.path does this automatically) and also to templateUrl when configuring routes. This avoids routes like example.com/tags/another and makes sure templates load properly.

Here's an example that works:

    <a href="/">Home</a> | 
    <a href="/another">another</a> | 
    <a href="/tags/1">tags/1</a>
<div ng-view></div>


app.config(function($locationProvider, $routeProvider) {
    .when('/', {
      templateUrl: '/partials/template1.html', 
      controller: 'ctrl1'
    .when('/tags/:tagId', {
      templateUrl: '/partials/template2.html', 
      controller:  'ctrl2'
    .when('/another', {
      templateUrl: '/partials/template1.html', 
      controller:  'ctrl1'
    .otherwise({ redirectTo: '/' });

If using Chrome you will need to run this from a server.