Single Page Application using AngularJs Tutorial
AngularJs is a powerful javascript framework for building dynamic web applications. It became insanely popular nowadays. The good thing about Angular is that it has a set of ready-to-use modules to simplify building of single page applications.
In this tutorial, we will show you how to build a simple single page application. Even though we will build a small app, you will learn the concepts and will be able to build larger apps.
Single Page Application
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.
Pros
No page refresh
When you are using SPA, you don’t need to refresh the whole page, just load the part of the page which needs to be changed. Angular allows you to pre-load and cache all your pages, so you don’t need extra requests to download them.
Better user experience
SPA feels like a native application: fast and responsive.
Ability to work offline
Even if user loses internet connection, SPA can still work because all the pages are already loaded.
Cons
More complex to build
You need to write pretty much javascript, handle shared state between pages, manage permissions, etc.
SEO
To index your SPA app, search engine crawlers should be able to execute javascript. Only recently Google and Bing started indexing Ajax-based pages by executing JavaScript during crawling. You need to create static HTML snapshots specially for search engines.
Initial load is slow
SPA needs to download more resources when you open it.
Client should have javascript enabled
Of course, SPA requires javascript. But fortunately, almost everyone has javascript enabled.
Angular Application
Every angular application starts from creating a module. Module is a container for the different parts of your application: controllers, service, etc.
var app = angular.module('myApp', []);
Lets define a simple controller:
app.controller('HomeController', function($scope) {
$scope.message = 'Hello from HomeController';
});
After we created module and controller, we need to use them in our HTML.
First of all, we need to include angular script and app.js that we built.
Then need to specify our module in ng-app attribute and controller in ng-controller attribute
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
</head>
<body ng-controller="HomeController">
<h1>{{message}}</h1>
<script src="app.js"></script>
</body>
</html>
If you done this correctly, you should see:
Since we have our module and controller set up and we know that Angular is working properly, we will start working on adding single page application support.
Recommendation
If your company is hiring a JavaScript developer, check out this JavaScript test prepared by our professionals. It will allow you to identify the best talents very easily!
ngRoute
Since we are making a single page application and we don’t want any page refreshes, we’ll use Angular’s routing capabilities.
We will use ngRoute module for that.
The ngRoute module provides routing, deeplinking services and directives for angular apps.
We need to include angular-route script after the main angular script.
<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>
Then we need to specify that our module depends on ngRoute module to be able to use it.
var app = angular.module('myApp', ['ngRoute']);
The next thing is to distinguish common HTML for every page. This HTML will be layout of the website.
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 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.
<!doctype html>
<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 $routeProvider service from the ngRoute module.
For each route, we need to specify templateUrl 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:
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'pages/home.html',
controller : 'HomeController'
})
.when('/blog', {
templateUrl : 'pages/blog.html',
controller : 'BlogController'
})
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'AboutController'
})
.otherwise({redirectTo: '/'});
});
Then we need to build controllers for every route (we already specified their names in routeProvider):
app.controller('HomeController', function($scope) {
$scope.message = 'Hello from HomeController';
});
app.controller('BlogController', function($scope) {
$scope.message = 'Hello from BlogController';
});
app.controller('AboutController', function($scope) {
$scope.message = 'Hello from AboutController';
});
Our pages will be simple:
home.html
<h1>Home</h1>
<h3>{{message}}</h3>
blog.html
<h1>Blog</h1>
<h3>{{message}}</h3>
about.html
<h1>About</h1>
<h3>{{message}}</h3>
Note that we don’t need to use html, head, body tags in our page. This pages will always be used inside layout as partial HTML.
Lets add links that will switch our pages. The final HTML looks like this:
<!doctype html>
<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>
<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>
Browsers don’t support loading resources from disk using ajax, so you can use any HTTP server to serve static HTMLs.
python -m SimpleHTTPServer
If you don’t want to do this, you can include your partial HTMLs to index.html using script tag with type text/ng-template.
When angular see this templates, it will load its content to the template cache and will not perform ajax request to get their content.
<!doctype html>
<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>
<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>
Conclusion
In this tutorial, you learned how to build a single page application using Angular. Now you can go ahead and create more complex single page apps.
Want to build single page application? Check this tutorial: SPA using AngularJs Step by StepClick To TweetDemo
http://plnkr.co/edit/ClBmOH3ljAWueRBdKGKR?p=preview
Coding skills assessment
If you're looking to hire software engineers and want to ensure that you only interview qualified candidates, we've created coding tests that can significantly simplify your hiring process:
Nicely written . Article clearly shows that great efforts have been taken by auther.
Is this necessary in this SPA?
Blog
{{message}}
About
{{message}}
it’s for example
Thank its very helpfull
Thanks this is really helpful for every one.
TY for the great tutorial.
Is it required that we get content from the controller or can we just put html on the index.html page? How is it helpful to put our content into the controller (app.js)?
Nicely written. Thanks
Good one for beginners to start with!!
Nice tutorials. Thanks for this tuts.
Great article. Thanks.
thank for your tutorial.
A bad article if you ask me,
it doesn’t show any application at all, just 3 relative static web pages without any functionality.
Precisely what I was after, grazie
Super-Ɗuper bloց! I am lօvving it!! Will bbe back ⅼatᥱr to read some more.
I am boօokmarking your feeds also
I am really ɦappy to glance at his website posts which inclludeѕ poenty
of useful data, thanks forr providing such information.
Thanks to you for hard Work.
Thank you for your smart work , It helped me a lot .
Congrats on the article! The first simple angularJs that explains clearly the routing process without creating monstruous confusing things.
Thank you for your effort.
It’s an amazing post for all the web users; they will
get advantage from it I am sure.
Hi, when typed directly http://localhost:8080/abc/pages/about.html instead of http://localhost:800/abc/#about –broken page will be displayed, how to prevent this or redirect to /login and not login.html
Thanks for the great article. You have mentioned good points.I faced an error: “Browser don’t support loading resources”.can you please solve my problem.
regards,
Bob
Angular JS Developer
i am stupeeeeeeddddddddddd
Very well written…I am an absolute beginner but I understood almost all of it.
1 request..can u pls mention all file names also OR the place on git where all files are uploaded..
Pingback: Single Page Application using AngularJs Tutorial – Tests4Geeks | SPA
Single page apps are becoming increasingly popular. Sites that mimic the single page app behavior are able to provide the feel of a phone/tablet application. Angular helps to create applications like this easily.
Great tutorial!
I’ve finally gotten many concepts behind angularjs.
Thanks
Good Tutorial, I really revised my Angular JS Concepts again
Thank you for your smart work , It helped me a lot
Pingback: Single Page Application using AngularJs Tutorial - Angular News
Good Tutorial, I really revised my Angular JS Concepts again
Good tutorial….Looking forward for more angularjs tutorials.
Great post! Thanks for sharing very powerful post, It’s very helpful. Keep it up.
This tutorial helped me to develop a small project for a class I am taking at the university. Thank you so much. However, I have a little problem. When navigating from one route to another then scrolling down a bit and navigate back to the previous route or a new one, the page remains at the same scroll position. This is annoying because if you scroll down to the bottom and click to jump to a new page the new page starts at the bottom as the previous page. I have been researching but the solutions are confused. For example:
router.subscribe(() => {
window.scrollTo(0, 0);
});
Where should I put that code?
Thanks for your help. I understand that you are doing this tutorial because you are very generous but could you help e to solve this one? Please.
Pingback: Single Page Application with AngularJS – learningonlinetutorials
suppose i want to create each html as one controller instated combining code in app.js. how can achieve ?
This website will really help everyone in providing the tools and information necessary for the people to develop and improve their website.
thank you this article helped a lot
This is nicely written tutorial but the same code giving problems with “angular.min.js” and “angular-route.min.js” with latest versions such as 1.6.5 and 1.6.9, but it works well with 1.4.7 version scripts.
Can someone let me know if they faced the issue with latest scripts and how they resolved them. Thanks.
Pingback: Django REST Framework Tutorial – DEVELOPPARADISE
angular.min.js:7 Uncaught Error: [$injector:modulerr]
It is really good the way it is explained and written. I loved it. Thanks a lot
Its very nice and helpful article. way of explanation is too simple.
Great work
Pingback: Frameworks for Developing Single Page Applications
any one tell how to maintain title descrption keyword in angular js single page application
Thanks for sharing