SPA in AngularJS

  • Single page application (SPA) is a web application that fits on a single page. All your code (JS, HTML, CSS) is retrieved with a single page load. And navigation between pages performed without refreshing the whole page.

Advantages of SPA :

  • No page flicker. Native application feel.
  • Client side routing and data rendering on client side.
  • Data is from server is in JSON format.

Disadvantages of SPA :

  • User must enable JavaScript.
  • Security.

You need to write javascript, handle shared state between pages, manage permissions, etc.

The SPA works on the two Elements:

    • Ng-Route
    • Ng-view

ngRoute

  • Since we are making a single page application and we don’t want any page refreshes, we’ll use Angular’s routing capabilities.
  • The ngRoute module provides routing, deeplinking services and directives for angular apps.
  • We need to include angular-route script after the main angular script.
  • Then we need to specify that our module depends on ngRoute module to be able to use it.

Syntax :

var app = angular.module('myApp', ['ngRoute']);
  • Then we need to specify the place where HTML of each page will be placed in our layout. There is a ng-view directive for that.

ng-view

  • ng-view is an Angular directive that will include the template of the current route (for example, /blog or /about) in the main layout file.
  • In plain words, it takes the file we specified for current route and injects it into the layout in the place of ng-view directive.

Example 1

<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.min.js"></script>
</head>
<body>

<div ng-view></div>

<script src="app.js"></script>
</body></html>

 

When HTML is ready, we need to configure our routes. We will use $route Provider service from the ngRoute module.
  • For each route, we need to specify template Url and controller.
  • If user will try to go to the route that does not exist, we can handle this by using otherwise function. In our case, we will redirect user to the “/” route:

Syntax :

var app = angular.module('myApp', ['ngRoute']);
Example 2 :
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.min.js"></script>
</head>
<body>
<script type="text/ng-template" id="pages/home.html">
<h1>Home</h1>
<h3>{{message}}</h3>
</script>
<script type="text/ng-template" id="pages/blog.html">
<h1>Blog</h1>
<h3>{{message}}</h3>
</script>
<script type="text/ng-template" id="pages/about.html">
<h1>About</h1>
<h3>{{message}}</h3>
</script>

<a href="#/">Home</a>
<a href="#/blog">Blog</a>
<a href="#/about">About</a>

<div ng-view></div>

<script src="app.js"></script>
</body></html>

Categorized in: