htmlangularjsngrouteng-view

My ng-view" directive doesn't function the way it is supposed to


I call ng-view, but the program never renders my home.html or cart.html pages. How do I get ng-view to work?

I have tried to use multiple types of references. I have called ng-view in different ways and nothing seems to work.

<!--My home.html:-->

<h2> HOME </h2>
<h1>{{message}}</h1>

<!--My cart.html:-->

<h2> CART </h2>
<h1>{{message2}}</h1>

Below are my index.html and app.js

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

myApp.config(['$routeProvider', function($routeProvider){
    $routeProvider.
    when('/home', {
        templateUrl: 'views/home.html',
        controller: 'homeController'
    })
    when('/cart', {
        templateUrl: 'views/cart.html',
        controller: 'cartController'
    })
    otherwise({
        redirect: '/home'
    });
}]);

myApp.controller('homeController', function($scope) {
    $scope.message = 'Home Page';
})

myApp.controller('cartController', function($scope){
    $scope.message2 = 'Cart Page';  
})
<!DOCTYPE html>
<html>
    <head>

        <title>Test Web App</title>

        <meta chrset="utf-8">

        <script src="lib/angular-route.js"></script>
        <script src="lib/angular.js"></script>
        <script src="lib/app.js"></script>

    </head>

    <body ng-app="myApp">
        
        <center><h1>Shopping Cart App</h1></center>
        

        <tr><td class="menu">
            <a href="#/home">Home</a>
            <a href="#/cart">Cart</a>
        </td></tr>
        <dev ng-view></dev>
    </body>
</html>

I expect that when clicking on either the home link or cart link, ng-view renders their templates.


Solution

  • You have syntax errors. Try putting dots before when

    myApp.config(['$routeProvider', function($routeProvider){
        $routeProvider
        .when('/home', {
            templateUrl: 'views/home.html',
            controller: 'homeController'
        })
        .when('/cart', {
            templateUrl: 'views/cart.html',
            controller: 'cartController'
        })
        .otherwise({
            redirect: '/home'
        });
    }]);