How to create routing in angular.js
Now a days we are using angular.js for creating one page application, So in this post i am going to explain you that how can we create routing in angular.js,
This is a very basic tutorial to create templating using angularjs, we started using angularjs over core jquery because In angularjs you follow MVC pattern, with this you can create a good standard for your project and reuse-ability of code.
So lets start tutorial step by step.
Create below mention directory structure
angularjs-routing (main dir) -index.html (file) -css (dir) ---style.css (file) -js (dir) ---app.js (file) -templates (dir) ---home.html (file) ---about.html (file) ---contactus.html (file)
Create index.html page this is you main landing page.
index.html
where ng-app=”rohitApp” is our angular.js module, you can replace it form your module name, but don’t forget to replace same in app.js.
Where..
will render all your sub pages like home, about, contactus pages which we are going to create.
Create style.css file under css folder where you will write your all css to design page
css/style.css
.box { width:33%; float:left; color:green; font-size:16px; } #content { text-align:center; margin-top:10%; } |
Now under templates directory create three pages home.html, about.html, contactus.html and paste below code in all files.
templates/index.html, about.html, contactus.html
You can also use below code both works same to bind data in angular js.
<h3> {{pageTitle}} h3> {{pageDescription}} |
{{pageTitle}}
{{pageDescription}}
Now final turn to create angular js files, create app.js file where we declare configuration of our app and declare routing and define controllers for each page.
js/app.js
var rohitApp = angular.module('rohitApp',['ngRoute']) .config(function($routeProvider){ $routeProvider // routing on home page .when('/', { templateUrl: 'templates/home.html', controller: 'homeController' }) //routing on about page .when('/about', { templateUrl: 'templates/about.html', controller: 'aboutController' }) //routing on contact page .when('/contactus', { templateUrl: 'templates/contactus.html', controller: 'contactusController' }) }); rohitApp // where rohitApp is our ng-app module .controller('homeController', function($scope) { $scope.pageTitle = "Home Page"; $scope.pageDescription = "I am Home Page." }) // calling abou controller .controller('aboutController', function($scope){ $scope.pageTitle = "About Page"; $scope.pageDescription = "I am About Page." }) // calling contact us controller .controller('contactusController', function($scope){ $scope.pageTitle = "Contact Us"; $scope.pageDescription = "I am Contact Us Page." }) |
If you have done all the task mentioned above then time to run your code on browser.
hit the your index page on browser and check it out.
Hope this will help you to understand routing feature of angular.js 🙂