0

AngularJS Routing with ngRoute

With AngularJS, you write Single Page Applications (SPAs) that uses only a single main page (e.g., index.html) to render its User Interface (UI) component. How the UI visually response to users happens within that single page. Each section of the page may display different content. SPAs generally do not redirect to another main page.

Routing is a way to change the content of one or more sections of the page. One way to do implement it is using ngRoute

Software Requirements

  • Windows 10
  • Notepad++ or Brackets
  • AngularJS 1.6
  • Main HTML must be HTML5-compliant

NgRoute

Before ngRoute can be used, you have to download it together with the main AngularJS library. Then include them in the main HTML file along with your AngularJS codes.

To navigate to those routes, provide href links to them.

Define Routes

The next thing to do is to define a number of routes using $routeProvider in the config function in myapp.js.

ngView Directive

The ngView directive as shown in the code snippet below is where the contents from the templateUrls get displayed per selected route, e.g., '/second'. The section is updated when the route changes.

Testing our SPA

Download the codes

https://github.com/Turreta/AngularJS-Routing-with-ngRoute

 

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert