Search code examples
angularjsangularjs-ng-route

ngRoute not working in angularJS


I have the following code

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="~/styles/bootstrap.min.css" rel="stylesheet" />
    <link href="~/styles/bootstrap-theme.min.css" rel="stylesheet" />

    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.js"></script>
</head>
<body ng-app="appName">
    <a href="/view1">view1</a>
    <a href="/view1">view2</a>
   <div>
    this is a dynamic message:  {{message}}
</div>
<div ng-view>

</div>
    <script type="text/javascript">
        var app = angular.module('appName', ['ngRoute']);

        app.config(function ($routeProvider) {
            $routeProvider.when('/', {
                templateUrl: 'pages/home.html',
                controller: 'HomeController'
            })
                .when('/view1', {
                    templateUrl: 'pages/about.html',
                    controller: 'FirstController'
                })
                .when('/view2', {
                    templateUrl: 'pages/contact.html',
                    controller: 'SecondController'
                })
                .otherwise({
                    redirectTo: '/'
                });
        });
        app.controller('FirstController', function ($scope) {
            $scope.message = 'first controller';
        });
        app.controller('SecondController', function ($scope) {
            $scope.message = 'Second controller';
        });
        app.controller('HomeController', function ($scope) {
            $scope.message = 'Home controller';
        });
    </script>
</body>
</html>

but when i click on the view1 or view2 anchor tag, nothing is happening and i get an error like this resource not found error

I dont get any error in the console, can anyone help me to figure out what exactly is wrong.


Solution

  • In your html you miss ngview directive add it.

    <div ng-view></div>

    For further help see this link http://viralpatel.net/blogs/angularjs-routing-and-views-tutorial-with-example/