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 :
- 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
- 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: