ngRoute not working

2019-09-02 06:25发布

问题:

My scripts are :

index.html

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>My Application</title>
</head>
<body>
    <div ng-view></div>

    <script src="/assets/vendor/angular/angular-1.2.16.min.js"></script>
    <script src="/assets/vendor/angular/extras/angular-route.js"></script>
    <script src="/assets/myapp/myApp.js"></script>
</body>
</html>

myApp.js

(function () {
    angular.module('myApp', ['ngRoute'])
           .config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
               $routeProvider.
                 when('/', {
                     template: '<h1>Home</h1>',
                     controller: function () {
                         console.log('Home');
                     }
                 }).
                 when('/books', {
                     template: '<h1>Books</h1>',
                     controller: function () {
                         console.log('Books');
                     }
                 });
               $locationProvider.html5Mode(true);
               console.log('routes configured');
           }]);
})();

I've wasted a lot of time trying to figure out what the problem might be with no luck. Am I missing something silly? thanks in advance for the help.

回答1:

Are you hosting your application in the root of your server? If not, then you will need to use the tag below in your head tag.

<base href="PATH_HERE" />

In addition, can you comment out the $locationProvider.html5Mode(true) line and get your app working in hash routing mode first?



回答2:

Just a question, but it is possible to add a function in the controller -> controller:function()? Because normally i would do it like this. controller:'mainController' and put the function in the mainController.