AngularJS How to Create Routes

Getting Started

I've used CDN for Bootstrap, Angular Js, and Angular Route JS so you need internet connection for them to work.

Creating our Main Page

First this is our main page named index.html. In here, we're gonna create a simple bootstrap navbar for navigation between routes.
  1. <!DOCTYPE html>
  2. <html ng-app="app">
  3. <title>AngularJS How to Create Routes</title>
  4. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  5. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  6. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.min.js"></script>
  7. </head>
  8. <nav class="navbar navbar-default">
  9. <div class="container-fluid">
  10. <!-- Brand and toggle get grouped for better mobile display -->
  11. <div class="navbar-header">
  12. <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
  13. <span class="sr-only">Toggle navigation</span>
  14. <span class="icon-bar"></span>
  15. <span class="icon-bar"></span>
  16. <span class="icon-bar"></span>
  17. </button>
  18. <a class="navbar-brand" href="#">AngularJS Route</a>
  19. </div>
  20.  
  21. <!-- Collect the nav links, forms, and other content for toggling -->
  22. <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
  23. <ul class="nav navbar-nav">
  24. <li><a href="#/">Home</a></li>
  25. <li><a href="#/about">About</a></li>
  26. <li><a href="#/blog">Blog</a></li>
  27. </ul>
  28. </div><!-- /.navbar-collapse -->
  29. </div><!-- /.container-fluid -->
  30. </nav>
  31. <div ng-view></div>
  32. <script src="angular.js"></script>
  33. </body>
  34. </html>

Creating our Templates

This are the pages that we are including in our routes. home.html
  1. This is the Homepage
about.html
  1. This the About Page
blog.html
  1. This the Blog Page

angular.js

Lastly, this contains our Angular.js scripts and our router. Take note that in routing, we need to add the dependency ngRoute to our app for it to work.
  1. var app = angular.module('app', ['ngRoute']);
  2.  
  3. app.config(function($routeProvider){
  4. $routeProvider
  5. .when('/', {
  6. templateUrl: 'home.html'
  7. })
  8. .when('/about', {
  9. templateUrl: 'about.html'
  10. })
  11. .when('/blog', {
  12. templateUrl: 'blog.html'
  13. })
  14. .otherwise({
  15. redirectTo: '/'
  16. });
  17. });
That ends this tutorial. Happy Coding :)

Comments

Submitted bykanberon Thu, 05/17/2018 - 16:42

Beautiful information! thank you for the tips

Add new comment