New version Angular 9

Refactoring and routing

In this part we will refactor the application. And add the detail template.



The source for this part is here:

The samples can be run with Firefox, in general or by running, into the directory,


    var app = angular.module('app',['customersModule','ngRoute']);
    <div ng-view></div>

At this point -NOTHING WILL WORK- anymore!!


AngularJS uses an internal routing system based on what follows the hash symbol. Each Angular address is associated with a route and a controller

The default route

Into the app.js file we will add the default route using the special "config" function. This function is run before the the controllers.

Note that the standard address would be "list" for which will be loaded the customers list template and will be associated the CustomersController.

In case no route is found (the otherwise) the user will be redirected to "list"

  function($routeProvider) {
      when('/customers/', {
        templateUrl: 'app/customers/list.html',
        controller: 'CustomersController'
        redirectTo: '/customers/'

At this point when reloading the page... everything will work :)

Going on the detail page

First we will create the route ,added after the first route. The special ":customerId" means that the second part of the url will be stored somewhere as customerId.

        when('/customers/:customerId', {
            templateUrl: 'app/customers/detail.html',
            controller: 'CustomerDetailController'

Now goes the controller, that will use (yes another..) service, $routeParams. The route params service contains the parameters declared inside the route! So we could have access to the customerId!

Note that the customer data is initialized as an object.

        $scope.customer = {};
            success(function(data, status, headers, config) {

The new template will be pretty simple. Note the ng-model that sets the variable on the scope.

<a href="#customers">Back to list</a><br>
<tr><td><label for="id">Id </label></td><td>{{}}</td></tr>
<tr><td><label for="first_name">First Name </label></td><td>{{customer.first_name}}</td></tr>
<tr><td><label for="last_name">Last Name </label></td><td>{{customer.last_name}}</td></tr>

Connecting all together

Now we should link the list page to the single item. To do this we will add on the list the reference, we will make the id linkable. Note the hash inside the href.

    <td><a href="#customers/{{}}">{{}}</a></td>

On the top of the detail we will add a link back to the list

    <a href="#customers">Back to list</a>

Another missing part is the automatic loading of the list. Inside the list controller, at the end of the initialization we will add the call to load data

    $scope.customers = [];
    $scope.loadData = function(url){
        success(function(data, status, headers, config) {

Last modified on: April 06, 2015