Angular Page Routing


Page routing is one of the Main concepts in angular js when you decide to create a complete app.

One of the interesting capabilities of  Single Page APP like Angular js is the ability to Fetch the  portions dynamically of a page without making a full page refresh. At the same time which allows you have to different html structure.

Angular accomplishes this using the “$routeProvider” service.  Using the route provider service you can provide the path for the page as well as the corresponding template for it.

 

First thing we have to define our Angular APP using  ng-app directive.

1. Here my app  name is “myApp”. It should be anything( just a name for your app)

2. ng-view is an angular directive where the dynamic content will be fetched based on the page routing and it will be displayed inside that HTML snippet.

<div ng-app=”myApp”><div ng-view></div></div> 

 Next we define the module using the angular.module construct as follows… make sure this code is referenced as a java script file.
angular.module('myApp', [])// defining my module here
    .config(function ($routeProvider) {
        $routeProvider
        .when('/', {template: '<div>This is the default Home Page</div>'})// first page path
        .when('/about', {templateURL: '/partials/about.html'})// second page path
});

You can either insert template code directly as using the template property as with the first .when chain for the $routeProvider, or you can reference an html file using the templateURLproperty, as we do in the second example that links to the /partials/about.html file.

As it was a single page APP, so we should have only one Master HTML template (index.html)

To test the Page Routing, create links in the index.html above/below the “ng-view” html structure but inside “ng-app” structure.

<div ng-app=”myApp”>
<a href=”/”>Home</a><a href=”/about”>About</a>
<div ng-view></div>
</div>

Now click on the link and it will shows the corresponding templates based on the page routing we provided in the js File.

Try it out here  “http://campus.codeschool.com/courses/shaping-up-with-angular-js&#8221;

 

About

Working For Cause Not For Applause

Tagged with: , , , , ,
Posted in Angularjs, web

Leave a comment