Part 23 AngularJS routing tutorial

In general, as the application becomes complex you will have more than one view in the application. Let's say you are building a single page application for a training institute and you have the following views
 - Home
 - Courses
 - Students 

We can take advantage of the Angular routing feature, to have a single layout page, and then inject and swap out different views depending on the URL the end user has requested. 

So in our application we will have the following views
Part 23 to 26 Routing in Angular 

index.html is the layout view
home.html, courses.html & students.html will be injected into the layout view(index.html) depending on the URL the end user has requested 

For example, if the user has requested http://localhost:51983/home, then home.html will be injected into the layout view (index.html). Similarly if the user has requestedhttp://localhost:51983/courses, then courses.html will be injected into the layout view (index.html). 

Preparing the angular application application to use routing : The AngularJS Route module is present in a separate JavaScript file. You can either download it from AngularJs.org and use it in the application or you can use the CDN link.

Part 24 Angular layout template

 The layout page for our example should be as shown below. 
 Part 23 to 26 Routing in Angular

Here are the steps
Step 1 : Copy and paste the following HTML in the body section of the page. 

<table style="font-family: Arial">
    <tr>
        <td colspan="2" class="header">
            <h1>
                WebSite Header
            </h1>
        </td>
    </tr>
    <tr>
        <td class="leftMenu">
            <a href="#/home">Home</a>
            <a href="#/courses">Courses</a>
            <a href="#/students">Students</a>
        </td>
        <td class="mainContent">
            <ng-view></ng-view>
        </td>
    </tr>
    <tr>
        <td colspan="2" class="footer">
            <b>Website Footer</b>
        </td>
    </tr>
</table>

Please note : 
1. The partial templates (home.html, courses.html & students.html) will be injected into the location where we have ng-view directive. 
2. For linking to partial templates we are using # symbol in the href attribute. This tells the browser not to navigate away from index.html. In a later video we will discuss how to get rid of the # symbol. 

At this point, if you navigate to index.html, the page looks as shown below. This is because we do not have the styles applied yet. 
 
Part 23 to 26 Routing in Angular
Step 2 : Add a stylesheet to your project. Name it styles.css. Copy and paste the following.

.header {
    width: 800px;
    height: 80px;
    text-align: center;
    
}
 
.footer {
    
    text-align: center;
}
 
.leftMenu {
    height: 500px;
    
    width: 150px;
}
 
.mainContent {
    height: 500px;
    
    width: 650px;
}
 
a{
    display:block;
    padding:5px
}
View Code

相关文章: