Search code examples
javascriptangularjsurl-routing

Why won't the routing work in this code?


This is just a little project to learn AngularJS, and I'm having trouble getting the routing to work. According to every tutorial I've looked over what I have here should work, but it doesn't, unfortunately. I would really appreciate it if someone could help me find my problem and help me fix it.

Here is my index:

<!DOCTYPE html>
    <html ng-app="danApp">
        <head>
            <script src="Scripts/angular.min.js"></script>
            <script src="Scripts/test.js"></script>
        </head>
        <body>
            <div ng-view></div>
        </body>
    </html>

View 1

<h1>View 1</h1>
<br><br><br><br>
<div>
   <input type="text" ng-model="nameText" >
      <ul>
         <li ng-repeat="things in info | filter: nameText | orderBy:'name'">
            Name: {{ things.name }} <br> Age: {{ things.age }} <br>
            City: {{ things.city }}
            <br>
         </li>
      </ul>
</div>

View 2

<h1>View 2</h1>
<br><br><br><br>
<div>
    <input type="text" ng-model="nameText" >
      <ul>
         <li ng-repeat="stuff in parents | filter: nameText | orderBy:'name'">
            Name: {{ stuff.name }} <br> Age: {{ stuff.age }} <br>
            City: {{ stuff.city }}
            <br>
         </li>
      </ul>
</div>

And, finally, my module, controllers, and routing code

"use strict";

 var danApp = angular.module('danApp', []);
               
 danApp.controller("danCtrl", function($scope) {
    $scope.info = [
        {name: 'Daniel', age: '22', city: 'Clarksville'},
        {name: 'Derek', age: '19', city: 'Jacksonville'},
        {name: 'Emily', age: '18', city: 'Erin'},
        {name: 'Denise', age: '27', city: 'Phoenix'}, 
    ];
 });
               
               
 danApp.controller("danCtrl2", function($scope) {
   $scope.parents = [
      {name: 'Lathan', age: '54', city: 'Stewart'},
      {name: 'Candy', age: '54', city: 'Stewart'},
      {name: 'Christine', age: '43', city: 'Erin'}
   ];
 });           
               
               
danApp.config(function ($routeProvider) {
   $routeProvider
      .when('/',
      {
         controller: 'danCtrl',
         templateUrl: 'views/view1.html'
      })
      .when('/view2',
      {
         controller: 'danCtrl2',
         templateUrl: 'views/view2.html'
      })
      .otherwise({redirectTo: '/'});
});


Solution

  • The issue is you need to include the angular-route.js or angular-route.min.js script which can be downloaded from the Angular website. In index.html add the script:

    <script src="Scripts/angular-route.min.js"></script>
    

    The module then needs to be added to your module:

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

    Plunkr