Kategorie
Bez kategorii

Task 9

Example number 37

<html ng-app="countryApp">
  <head>
    <meta charset="utf-8">
    <title>Angular.js Example</title>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.10/angular.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.10/angular-route.min.js"></script>
    <script>
      var countryApp = angular.module('countryApp', ['ngRoute']);

      countryApp.config(function($routeProvider) {
        $routeProvider.
          when('/', {
            templateUrl: 'country-list.html',
            controller: 'CountryListCtrl'
          }).
          when('/:countryName', {
            templateUrl: 'country-detail.html',
            controller: 'CountryDetailCtrl'
          }).
          otherwise({
            redirectTo: '/'
          });
      });

      countryApp.controller('CountryListCtrl', function ($scope, $http){
        $http.get('countries.json').success(function(data) {
          $scope.countries = data;
        });
      });

      countryApp.controller('CountryDetailCtrl', function ($scope, $routeParams){
        $scope.name = $routeParams.countryName;
      });
    </script>
  </head>
  <body>
    <div ng-view></div>
  </body>
</html>

This is an example of using links with routes for navigation between views in simple AngularJS web application by uses the ngRoute module to implement routing. The web application displays a list of countries and allows the user to click on a country to see more information about it.

The code begins by defining a new AngularJS module named countryApp. The ngRoute module is injected as a dependency into the countryApp module. Then, the $routeProvider is used to configure the routes for the application.

There are two routes defined: '/’ and ’:countryName’. The first route maps to the CountryListCtrl controller and displays a list of all countries. The second route maps to the CountryDetailCtrl controller and displays details about a specific country based on the countryName parameter passed in the URL.

The CountryListCtrl controller retrieves the list of countries from a countries.json file using the $http service and stores it in the $scope.countries variable. The CountryDetailCtrl controller retrieves the countryName parameter from the URL using the $routeParams service and stores it in the $scope.name variable.

Finally, the ng-view directive is used in the body of the HTML to specify where the templates for the different views should be displayed. When the user navigates to a different route, AngularJS will automatically load the appropriate template and controller based on the route configuration.