AngularJS Views

Single Page Application is supported by AngularJS using the concept of multiple views only on a single page. In AngularJS, this is achieved by ng-view and ng-template directives and also by $routeProvider services.

Let us understand ng-view, ng-template and $routeProvider in detail.


ng-view

ng-view is a tag that just creates a place holder where a view (html or ng-template) can be placed according to the configuration.

Use of ng-view

Using ng-view define a div within the module.

<div ng-app = "mainApp">
   ...
  <div ng-view></div>

</div>  

ng-template

This directive is used to create an HTML view by making use of the script tag. The "id" attribute in this directive is used by the $routeProvider so that it can map a view with the controller.

Use of ng-template

Using type as ng-template, define a script block in the main module.

<div ng-app = "mainApp">
   ...
	
   <script type = "text/ng-template" id = "addStudent.htm">
      <h2> Add Student </h2>
      {{message}}
   </script>

</div>  

$routeProvider

The key service which sets the configuration of URLs, maps them with the ng-template or corresponding HTML views and helps in attaching them with the controller is the $routeProvider service.

Use of $routeProvider

After defining a script within the main module, set the routing configuration.

<div ng-app = "mainApp">
   ...
	
   <script type = "text/ng-template" id = "addStudent.htm">
      <h2> Add Student </h2>
      {{message}}
  </script>

</div> 

There are certain important points in the above example that need to be understood

  • The $routeProvider is defined as a function under the config of mainApp, using key as '$routeProvider'.
  • $routeProvider.when defines a URL "/addStudent" that has been further mapped to "addStudent.htm". addStudent.htm must necessarily be present in the same path as main HTML page. In case, the HTML page is undefined, we must use id="addStudent.htm" along with ng-template. We have used ng-template in the given example.
  • "otherwise" has been used to set the default view.
  • To set the corresponding controller for the view, "controller" has been used.