AngularJS Framework : Routing III - Extracting and using parameters from routes
Picture from How to structure large angularJS applications
The following sections are largely based on Introduction to Angular.js in 50 Examples (part 2).
We'll start from where we left off (Routes II - separate url template files). In this section, we'll extract and use parameters from routes. As in the previous chapter, two template files are used here. (country-list.html and country-detail.html).
We will modify this:
countryApp.controller('CountryDetailController', function ($scope, $routeParams){ console.log($routeParams); });
To this:
countryApp.controller('CountryDetailController', function ($scope, $routeParams){ $scope.name = $routeParams.countryName; });
Here is our new code (extract_param.html):
<html ng-app="countryApp"> <head> <meta charset="utf-8"> <title>Angular.js Example</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.min.js"></script> <script> var countryApp = angular.module('countryApp', ['ngRoute']); countryApp.config(function($routeProvider) { $routeProvider. when('/', { templateUrl: 'country-list.html', controller: 'CountryListController' }). when('/:countryName', { templateUrl: 'country-detail.html', controller: 'CountryDetailController' }). otherwise({ redirectTo: '/' }); }); countryApp.controller('CountryListController', function ($scope, $http){ $http.get('http://www.bogotobogo.com/AngularJS/files/Route2/countries.json').success(function(data) { $scope.countries = data; }); }); countryApp.controller('CountryDetailController', function ($scope, $routeParams){ $scope.name = $routeParams.countryName; }); </script> </head> <body> <div ng-view></div> </body> </html>
The root url just lists country names as before:
It is rendered like this when we types in a country name after '#/':
Note that we are able to use name variable in country-detail.html:
<h1> {{ name }} </h1>
This is because we are extracting the name from $routeParams and passing it to $scope:
countryApp.controller('CountryDetailController', function ($scope, $routeParams){ $scope.name = $routeParams.countryName; });
Continued at Routes IV - navigation between views using links.
AngularJS
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization