AngularJS: ngRoute Not Working

2019-01-07 01:05发布

I am tying to get this simple routing to work and can't figure out what is the problem.

This is the HTML:

<html lang="en" ng-app="app">
     .
     .
     .  
     <a href="#voip">
       <div class="col-lg-3 service">
        <img src="assets/img/voip.svg"/>
        <h4 ng-bind-html="content.home.voip_header"></h4>
        <p ng-bind-html="content.home.voip_txt"></p>
      </div>
    </a>

    <section id="view">
      <div ng-view></div>
    </section>

This is the routing:

var app = angular.module('app',[
  'ngRoute',
  'ngSanitize'
]);
    app.config(['$routeProvider',function($routeProvider){
      $routeProvider
      .when('/voip',{
        templateUrl:'assets/templates/voip.html'
      });
    }]);

The template is loaded if I specify 'otherwise' as below. I thought maybe I am using the wrong syntax in my href attribute, but I looked everywhere and seems like this is how it should be.

      .otherwise({
       redirectTo:'/voip'
      })

Another thing is, if I listen to $routeChangeSuccess, the event is triggered, yet the view is not loaded.

Any ideas?

2条回答
Root(大扎)
2楼-- · 2019-01-07 01:17

try to use exclamation marks in html5 + ajs 1.6.

for example instead of href="#home"..... write href="#!home". It worked for me after 4 hours of head scratching.

查看更多
我只想做你的唯一
3楼-- · 2019-01-07 01:25

It's properly because you are using angular 1.6 and there has been a change the default hash-prefix:

Due to aa077e8, the default hash-prefix used for $location hash-bang URLs has changed from the empty string ('') to the bang ('!'). If your application does not use HTML5 mode or is being run on browsers that do not support HTML5 mode, and you have not specified your own hash-prefix then client side URLs will now contain a ! prefix. For example, rather than mydomain.com/#/a/b/c the URL will become mydomain.com/#!/a/b/c.

If you actually want to have no hash-prefix, then you can restore the previous behavior by adding a configuration block to you application:

appModule.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix(''); }]); Source

So you have some options:

1. Set HTML5mode true

$locationProvider.html5Mode(true);

and in html set base in html header:

<base href="/">

Lastly change <a ng-href="#voip"> to

<a ng-href="voip">

2. Use the 1.6 way
Change
<a ng-href="#voip">
to
<a ng-href="#!voip">

3. Go back to old behaviour from 1.5 - set hash prefix manually

app.config(['$locationProvider', function($locationProvider) {
  $locationProvider.hashPrefix('');
}]);
查看更多
登录 后发表回答