Click here to Skip to main content
15,118,573 members
Articles / Programming Languages / Javascript
Technical Blog
Posted 8 Dec 2016

Tagged as

Stats

2.3K views

More Angular Routing Topics

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
8 Dec 2016CPOL4 min read
In this blog post, you will learn more things you can do with routing such as specifying the controller to use, aliasing the controller using “as”, passing parameters to a page and programmatically calling a route.

In the last blog post you were introduced to routing in Angular (v1.x). You learned the basics of how to route to different HTML fragments using the routing features of Angular. In this blog post, you learn more things you can do with routing such as specifying the controller to use, aliasing the controller using “as”, passing parameters to a page and programmatically calling a route.

Set the Controller Name

If the target page for your route has some functionality that needs to be performed, you will have a controller associated with that page. An additional property you can set on the route object when configuring your routes is the controller property. Set this property to the name of the controller function for that page.

JavaScript
.when('/page2/',
{
  templateUrl: 'page2.template.html',
  controller: 'Page2Controller'
})

When using the controller property in your route, you must include the .js file that contains the code for that controller on your main HTML page.

JavaScript
<script src="app.module.js"></script>
<script src="index.controller.js"></script>
<script src="page2.controller.js"></script>

Below is the code for the Page2Controller. This controller is a simple sample that just sets a message property with some hard-coded text using the $scope application object.

JavaScript
(function () {
  'use strict';
  
  angular.module('app')
   .controller('Page2Controller', Page2Controller);
  function Page2Controller($scope) {
    $scope.message = 'Page 2 says \'Hello\'';
  }
})();

Once the message property is set on the $scope object, that value can be displayed on the HTML fragment using the data binding syntax.

JavaScript
<h2>{{message}}</h2>

Alias the Controller

When developing Angular pages, it is always a good idea to alias your controller using the “as” syntax as shown in the following code snippet.

JavaScript
<div ng-app="app"
      ng-controller="IndexController as vm"

However, this syntax is only used when you are setting the ng-controller directive on your main page. On your page fragments, you are not using this directive. Not to worry, the route object supports a controllerAs property so you can set this alias name.

JavaScript
.when('/page1',
{
  templateUrl: 'page1.template.html',
  controllerAs: 'page1',
  controller: 'Page1Controller'
})
.when('/page2',
{
  templateUrl: 'page2.template.html',
  controllerAs: 'page2',
  controller: 'Page2Controller'
})

When you use the "as" syntax, the application scope is passed into your controller as ‘this’. Assign 'this' to a local variable in your controller, then create any properties you want on the application scope so you can use those properties in your HTML. In the Page1Controller, shown below, create a property named message and set it to a hard-coded string.

JavaScript
(function () {
  'use strict';
  
  angular.module('app')
   .controller('Page1Controller', Page1Controller);
  function Page1Controller() {
    var vm = this;
    vm.message = 'Hello from Page One!';
  }
})();

To use the message property on your HTML page, prefix the property name with the value you set in the controllerAs property. To display the value in the message property in your page1.template.html page, you use the following code:

JavaScript
<p>{{page1.message}}</p>

Again, if you are specifying controllers in your routing, make sure you include the appropriate .js files on your index.html page.

JavaScript
<script src="app.module.js"></script>
<script src="index.controller.js"></script>
<script src="page1.controller.js"></script>
<script src="page2.controller.js"></script>

Pass a Parameter to a Route

Sometimes, you need to pass a parameter to a page. You can also pass parameters to a route. In the anchor tag shown below, you are passing a value of 12345 to the route defined by /page2.

JavaScript
<a href="#/page2/12345" 
   class="btn btn-primary">
  Page 2 with parameter
</a>

Keep your original /page2 route, but add an additional route using a when() function. After the /page2, add another forward slash followed by a colon (:) and a variable name such as id.

JavaScript
.when('/page2',
{
  templateUrl: 'page2.template.html',
  controllerAs: 'page2',
  controller: 'Page2Controller'
})
.when('/page2/:id',
{
  templateUrl: 'page2.template.html',
  controllerAs: 'page2',
  controller: 'Page2Controller'
})

In your Page2Controller function, you now need to have the $routeParams injected. Add the $routeParams service as a parameter to your Page2Controller function. Before you use the parameter, test to see if the value was passed in by using an if statement as shown in the following code:

JavaScript
function Page2Controller($routeParams) {
  var vm = this;
  if ($routeParams.id) {
    vm.message = 'The id passed in was: '
                 + $routeParams.id;
  }
  else {
    vm.message = 'Page 2 says \'Hello\'';
  }
}

If you need more than one value passed, just add another route such as the following:

JavaScript
.when('/page2/:id/:extraText',
{
  templateUrl: 'page2.template.html',
  controllerAs: 'page2',
  controller: 'Page2Controller'
})

In your index.html, you call this route using the following:

JavaScript
<a href="#/page2/123/abc" 
   class="btn btn-primary">
  Page 2 with 2 parameters
</a>

In the controller for this page, add another test for this additional parameter:

JavaScript
if ($routeParams.extraText) {
  vm.message = 'extraText=' + $routeParams.extraText;
}

Programmatically Calling a Route

Many times, when running code in one of your controllers, you will have a need to redirect the user to a new route. This is accomplished by calling the path() function on the $location service and then passing in one of your defined routes. The following code shows a couple of functions you may have in a controller. If either of these functions are called, the URL of the browser is set to the new path, and then the user is directed to the appropriate page. Make sure you add the $location service as a parameter to your controller function.

JavaScript
function IndexController($location) {
  function goToPage1() {
    $location.path("/page1");
  }
  function goToPage2() {
    $location.path("/page2");
  }
}

Summary

In this blog post, you learned how to route to page fragments, but specify the controller to use with that page. The controller and controllerAs properties of the route object are used to set the information for the controller to be used with a page. You are able to add one or more parameters to a route. The $routeParams service can retrieve as many different parameters passed to a controller as you want. Use the $location service to programmatically direct a user to a route in your Angular application.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Paul D. Sheriff
Employed (other) PDS Consulting
United States United States
Paul has been in the IT industry over 34 years. In that time he has successfully assisted hundreds of companies architect software applications to solve their toughest business problems. Paul has been a teacher and mentor through various mediums such as video courses, blogs, articles and speaking engagements at user groups and conferences around the world. Paul has 25 courses in the www.pluralsight.com library (https://www.pluralsight.com/author/paul-sheriff) on topics ranging from JavaScript, Angular, MVC, WPF, XML, jQuery and Bootstrap. Contact Paul at psheriff@pdsa.com.

Comments and Discussions

 
-- There are no messages in this forum --