Search code examples
javascriptangularjsngroute

Understanding routing in Angular JS


I am trying to understand why this code is not working (I was checking info about this topic, but people have different answers for this question). I typed a very simple example to understand routers in Plunker, but I can not do it work...

This is my index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
    <script src="app.js"></script>
  </head>

  <body>
  <div ng-view></div>    

    <a href="#red">Red</a>
    <a href="#green">Green</a>
    <a href="#blue">Blue</a>


  </body>

And this is my app.js:

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

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
});

app.config(function($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl : "index.html"
    })
    .when("/red", {
        templateUrl : "red.html"
    })
    .when("/green", {
        templateUrl : "green.html"
    })
    .when("/blue", {
        templateUrl : "blue.html"
    });
});

My red.html / blue.html and green.html are very simple, like this (for each color):

<p>red!</p>

But It doesn't update ng-view... Also, I tried this:

<a href="#/red">Red</a>
<a href="#/green">Green</a>
<a href="#/blue">Blue</a>

But nothing...


Solution

  • Your code does not have references for angular route,

      <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.10/angular.min.js"></script>
      <script src="https://code.angularjs.org/1.2.0rc1/angular-route.js"></script>
    

    DEMO