My Technical Notes

Monday, 12 October 2015

Angular $routeParams Example


<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body ng-app="app">
    <script type="text/ng-template" id="view.html">
        <div>
            Forename: {{forename}}
        </div>
        <div>
            Surname: {{surname}}
        </div>
    </script>

    <div ng-view>

    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular-route.js"></script>
    <script>
        var app = angular.module('app', ['ngRoute']);

        app.config(function ($routeProvider) {
            $routeProvider
                .when('/person/:forename/:surname', { templateUrl: 'view.html', controller: 'personCtrl' });
        });

        app.controller('personCtrl', function ($scope, $routeParams) {
            $scope.forename = $routeParams.forename;
            $scope.surname = $routeParams.surname;
        });
    </script>
</body>
</html>

Running `.../index.html#/person/Tahir/Hassan` will give us the message:


Forename: Tahir
Surname: Hassan

Another method would be to use the HTTP style parameters: `.../index.html#/person?forename=Tahir&surname=hassan`.

No comments: