简体   繁体   中英

Angular Routes (tutorial) not working

I am following google's angular tutorial log (different names for stuff I need), and I cannot get the routing to work correctly for the life of me. If I take the # out of the hrefs, i'll get a "Cannot GET" error". With the #, the URL changes but nothing happens.

controllers.js

var AppControllers = angular.module('AppControllers',[]);

AppControllers.controller('homeCtrl', ['$scope', '$http',
    function($scope, $http){
  $http.get('javascripts/apprentices.json').success(function(data){
        $scope.apprentices = data;

  });
  $scope.orderProp = 'semester';
}]);

AppControllers.controller('apprenticeCtrl',['$scope', '$routeParams',
    function($scope, $routeParams) {
console.dir('hi');
      $http.get('javascripts/person.json').success(function(data) {
        // $scope.apprentices = data;
      });
    }]);

app.js

var App = angular.module('App',[
  'ngRoute',
  'AppControllers']);

App.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
    when('/apprentices', {
        templateUrl: 'views/apprentice.html',
        controller: 'apprenticeCtrl'
      }).
      otherwise({
        templateUrl:'../views/home/index.html',
                redirectTo: '/asfsfsf'
      });
  }]);

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title></title>
    <link rel="stylesheet" href="/stylesheets/style.css">
    <script src="javascripts/angular/angular.js"></script>
    <script src="javascripts/angular/angular-route.js"></script>
    <script src="javascripts/app.js"></script>
    <script src="javascripts/controllers.js"></script>
    <body>
      <div ng-app="App">
        <div ng-controller="homeCtrl">
          code
      </div>
      <div ng-view></div>
    </body>
  </head>
</html>

Looks like you just need to move the ng-app tag up to the body element. The scope of the app is defined in the ng-app element and not it's siblings:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title></title>
    <link rel="stylesheet" href="/stylesheets/style.css">
    <script src="javascripts/angular/angular.js"></script>
    <script src="javascripts/angular/angular-route.js"></script>
    <script src="javascripts/app.js"></script>
    <script src="javascripts/controllers.js"></script>
    <body ng-app="App">
      <div>
        <div ng-controller="homeCtrl">
          code
      </div>
      <div ng-view></div>
    </body>
  </head>
</html>

Another option would be to put the ng-view div inside the ng-app div if so desired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM