Wednesday 30 September 2015

How to create single page application using angular js

Hi guys, Angular js a grate framework to build single page application. Angularjs is most popular framework to build single page application.
In this post I am showing you that how to use routing (ng-route) to build a single page app using angular.
For routing we have to include angular-route.js in our angular project. and our html will look like and for rendering the different views of our application we will use ng-view directives in our body section where we want to render the different views.
I have also included 2 more files app.js and controller.js.
In app.js file we will define the app also write the routing code. and in controller.js we will write the controllers.
We can create multiple controllers in a single js files. but If you have lots of functionality than you should create different files for different controllers. I have created a single file for controllers controller.js
I have also created a basic navigation bar for switching the view.



In app.js file I am defining app and also defining routes using ng-route. I have added ng-route dependency in my module. I have to use the config function for configuring the routes. you can see in the code snippet.




  • when('/view1'): The view1 view will be shown when the URL hash fragment is /view1. To construct this view, Angular will use the view1.html template and the view1 controller.
View1.html

  • when('/view2'): The view2 view will be shown when the URL hash fragment matches '/view2', . To construct the phone details view, Angular will use the view.htmltemplate and the view2 controller.
View2.html

  • otherwise({redirectTo: '/'}): triggers a redirection to when the browser address doesn't match either of our routes.
Now you can see it in action. you can switch between views by just clicking on navbar and the view will change. check the example below


No comments:

Post a Comment