How to config routeProvider and locationProvider in angularJS?

前端 未结 6 1621
忘掉有多难
忘掉有多难 2020-11-29 00:03

I want to active html5Mode in angularJS, but I don\'t know why it\'s not working. Is there anything wrong with my code?



        
6条回答
  •  情深已故
    2020-11-29 00:44

    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 () 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:

    
    

    And

    app.config(function($locationProvider, $routeProvider) {
      $locationProvider.html5Mode(true);
      $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.

提交回复
热议问题