wrath1888
wrath1888

Reputation: 49

Angular routing for newbie

I've just started learning angular & creating the first app. Help me please with routing.

Folder Structure

spa/ index.html controllers/ controllers.js images/ javascript/ app.js resources/ angular-route.js angular.js views/ cars.html home.html login.html profile.html

The pages from "/views" are not displayed. Here's my code.

index.html

<!DOCTYPE html>
<html lang="en" data-ng-app="app">
  <head>
    <meta charset="UTF-8">
    <title>5 Angular</title>
    <script src="resources/angular.js"></script>
    <script src="controllers/controller.js"></script>
    <script src="javascript/app.js"></script>
    <script src="resources/angular-route.js"></script>
  </head>
  <body ng-controller="mainCtrl">
    <nav>
      <ul class="navbar">
        <li>
          <a href = "#home">Home</a>
        </li>
        <li>
          <a href = "#Login">Login</a>
        </li>
        <li>
          <a href = "#profile">Profile</a>
        </li>
        <li>
          <a href = "#cars">Cars</a>
        </li>
      </ul>
    </nav>
    <ng-view></ng-view>
  </body>
</html>

cars.html

<h1>Cars Page</h1>

home.html

<h1>Home Page</h1>

login.html

<h1>Login Page</h1>

profile.html

<h1>Profile Page</h1>

app.js

angular.module('app', ['ngRoute'])
.config(function($routeProvider, $locationProvider){
$routeProvider
.when('/', {
templateUrl: 'views/home.html'
})
.when('login', {
templateUrl: 'views/login.html'
})
.when('cars', {
templateUrl: 'views/cars.html'
})
.when('profile', {
templateUrl: 'views/profile.html'
})
otherwise('/');
});

Controller

angular.module('app', ['ngRoute'])
.controller("mainCtrl",function($scope){

})

Upvotes: 1

Views: 154

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136184

Once you create app module in app.js like angular.module('app', ['ngRoute']) You shouldn't recreate the app module in controller.js again which will flush all the initial registered component like here you did .config block for router settings.

It should be

angular.module('app')

instead of

angular.module('app', ['ngRoute'])

Additionally login anchor should be #/login instead of #Login because $routerProvider has condition on login. Also notice there should be a slash after the hash in the href.

<a href = "#/login">Login</a>

Upvotes: 2

Related Questions