Features and advantages of single page applications are
AngularJS is a client side library and it’s templating is based on two way data binding i.e. it changes or updates the view whenever the model is changed or updated. Unlike traditional server-side HTML programming, the controller and model state are maintained within the client browser in AngularJS framework. Here new pages are generated without any interaction with a server.The HTML template is compiled in the browser.
So, we wil move on with AngularJS. AngularJS provides two directives ‘ng-route’ and ‘ng-view’ which can be used to make a single page web application.
‘ng-route’ manages the routing for a web application.Routing means when we click on click on a link defined by anchor tag(), we get redirected to that particular link. ‘ng-route’ is used to handle those routes.
‘ng-view’ renders the page template on a view which depends upon the router. In our example we will use two views ,one is home and another is other view.
Now we are going to discuss the concept with a sample example.In this example we have created three HTML pages.
and one script ‘script.js’.
<title>Single Page Application using Angularjs</title>
<!–This DIV loads templates depending upon route.–>
In the above page we have used angular.min.js(1.4) and angular-route.min.js for enabling angular in our application ‘myApp‘ .Here in the ng-view templates will be rendered according to the router.
This is home page
This is other page
Above two pages(home.html and other.html) are two templates with sample text, to be displayed depending upon routing.
Next, we will focus on our angular code which is written in script.js.
//Controller code for mainController
//Controller code for otherController
In the above code first we have created an angular module ‘app‘ with our application ‘myApp‘. We have also installed the ‘ngRoute’ module.
Next, we have made a configuration to our app with $routeProvider which is used to configure routes.
As we can see in $routeProvider when a URL hits ,corresponding file URL is being passed and it will be loaded into the ng-view to render.More templates can be added depending upon needs. Here we are also assinging a controller. AngularJS will invoke the controller with a $scope object.In AngularJS, $scope is the application object (the owner of application variables and functions).
How it works
How to run the application
Files need to be created as mentioned above or reader can download the complete source code from Github. Code needed to be put in a web server(e.g. XAMPP, WAMP etc.) and then it can be run trough browser.