Sachith Muhandiram
Sachith Muhandiram

Reputation: 2972

404 Not Found in AngularJS

I just started AngularJS. When I try to implemt following example, I am getting

404 Not Found

This is my main.html

<!DOCTYPE html>
<html ng-app="demoApp">
<script src="angular.min.js"></script>
<head>
    <title>main page</title>
</head>
<body>

<div ng-view></div>

<script>
var demo = angular.module('demoApp',[]);

demo.config(function ($routeProvider){
    $routeProvider
        .when ('foo',{
            controller : 'SimpleController',
            templateUrl: 'first.html'
        })      
    });

demo.controller('SimpleController',function($scope){
    $scope.customers = [
        {name: 'sac',city:'abcd'},
        {name: 'mac',city:'efgh'},
        {name: 'nalaka',city:'ijkl'}
    ];
});
</script>

</body>
</html>

My first.html

<ul>
    <li ng-repeat="cus in customers ">{{ cus.name }}</li>
</ul>

When I visit localhost/foo I am getting 404 exception. I just started AngularJS. So any help/guide to solve this problem will be a great help for me.

Thanks in advance

Upvotes: 3

Views: 10740

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136134

You should refer angular-route.min.js file on page & then include ngRoute module in your application.

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

You should correct your .when condition to below

.when('/foo',

As you did't enabled html5mode in your routing, you could access the page via localhost/#/foo URL.

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

demo.config(function($routeProvider) {
  $routeProvider
    .when('/foo', {
      controller: 'SimpleController',
      templateUrl: 'first.html'
    })
    // By default it will open foo
    .otherwise({redirectTo: '/foo'})
});

demo.controller('SimpleController', function($scope) {
  $scope.customers = [{
      name: 'sac',
      city: 'abcd'
    },
    {
      name: 'mac',
      city: 'efgh'
    },
    {
      name: 'nalaka',
      city: 'ijkl'
    }
  ];
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-route.min.js"></script>
<div ng-app="demoApp">
  <div ng-view></div>
  <script type="text/ng-template" id="first.html">
    Content of the template.
  </script>

</div>

Upvotes: 3

Related Questions