New Pluralsight Course on Unit Testing Released by Paul Sheriff

Unit TestingPluralsight is your go-to website for thousands of developer videos. Paul now has 13 courses available in the Pluralsight library. His latest is described below...

Basics of Unit Testing for C# Developers 

Every developer knows they should be creating Unit Tests to improve the quality of their applications. This course will walk you through creating unit tests using Visual Studio. You will see how easy it is to get started with creating unit tests. In addition, you will learn how to simplify the unit test process by creating data-driven tests. Finally, you will automate your unit tests by scheduling them to run via the command line utility VSTest.Console.
http://www.pluralsight.com/courses/basic-unit-testing-csharp-developers
Promo Video: http://bit.ly/2swbq56

Paul's Pluralsight Videos

In-Person Training / Mentoring

Would you like to experience our professional mentoring or training in person? Call Fairway Technologies today to discuss your training needs.

An Alternative to HTML Tables

I have long had a problem with using HTML tables to display data to the user. I have an even bigger problem with editing on a table, but that is a different discussion. An HTML table is easy to implement for a developer, and this is normally why developers use them. However, a table is not always the best method for conveying data to a user, especially when that data is most likely viewed on a mobile device. Of course, there are always exceptions to this rule, but these should be "the exception" and not the rule. There are many reasons why a table is not suitable for user consumption.

  • A table presents too much data on the screen so the user's eye has too much to try to concentrate on.
  • A user will get much more tired at the end of the day using a table as opposed to other display types.
  • The user cannot distinguish between the data in each column since each column is very uniform and nothing stands out.

The above are just some of the reasons why a table might not be the appropriate choice for displaying a list of data to the user. Look at Figures 1 and 3 for an example of a normal HTML table displayed in both a normal browser and on a mobile device. Then look at Figures 2 and 4 which should the alternative display of the same data on a desktop browser and a mobile device. As you can see the alternative design displays the data in a much easier-to-read format.

Using a HTML Table

A list of product data in a normal HTML table renders fine on a desktop browser, as illustrated in Figure 1. However, if you display that same product data on a mobile browser, you might only see the left most columns as illustrated in Figure 2. On some mobile browsers, they may render the table so small that it is hard to read. Either way, the user is forced to interact with their phone to view the data. They will either have to scroll left to right, or maybe pinch or spread with their fingers.


Figure 1: An HTML table rendered on a desktop browser.


Figure 2: An HTML table rendered on a mobile browser.

Using a Bootstrap Panel

Instead of using an HTML table, you might display a list of Bootstrap panel controls that contain your product data. In the sample shown in Figure 3 you see the same data, but the most important data, the product name, is displayed in the panel header area. The other information about the product is displayed within the body of the panel. The actions you can take are displayed within the panel footer area. As you can see this list of data looks just as good on a normal desktop browser (Figure 3) as on a mobile browser (Figure 4).


Figure 3: An alternative approach to a list of data rendered on a desktop browser.


Figure 4: An alternative approach to a list of data rendered on a mobile browser.

Create Mock Data Classes

Instead of messing with a database, create three simple classes to build a collection of Product objects that can be rendered on an MVC page. Figure 5 illustrates the properties and methods of each of the 3 classes. To view the code for these classes, see the instructions at the end of this blog post on how to download the sample.


Figure 5: A set of 3 product classes help us load mock product data for this sample

The MVC Controller

You need a MVC controller to load the data and feed that data to the CSHTML pages used to render our two pages of product data. Below is the code from the MVC controller. The TableSample and AlternateTableSample methods create an instance of the TrainingProductViewModel class and call the LoadProducts method to build the Products property in the view model. It is the collection property that is used to display the list of data in both pages.

public class HomeController : Controller
{
  public ActionResult Index() {
    return View();
  }
  public ActionResult TableSample() {
    TrainingProductViewModel vm = new TrainingProductViewModel();
    vm.LoadProducts();
    return View(vm);
  }
  public ActionResult AlternateTableSample() {
    TrainingProductViewModel vm = new TrainingProductViewModel();
    vm.LoadProducts();
    return View(vm);
  }
}

Create the HTML Table

The TableSample page is the one that renders the standard HTML table. Below is the code from the TableSample.cshtml page.

@model AlternativeTable.TrainingProductViewModel
@{
  ViewBag.Title = "Table Sample 1";
}
<h2>Table Sample 1</h2>
@using (Html.BeginForm()) {
  <div class="table-responsive">
    <table class="table table-bordered
                  table-condensed table-striped">
      <thead>
        <tr>
          <th>Product Name</th>
          <th>Introduction Date</th>
          <th class="text-right">Price</th>
          <th>URL</th>
          <th>Delete</th>
        </tr>
      </thead>
      <tbody>
        @foreach (TrainingProduct item in Model.Products) {
          <tr>
            <td>
              <a href="#"
                 title="Edit Product">
                @item.ProductName
              </a>
            </td>
            <td>@item.IntroductionDate.ToShortDateString()</td>
            <td class="text-right">@item.Price.ToString("c")</td>
            <td>@item.Url</td>
            <td>
              <a href="#"
                 title="Delete Product"
                 class="btn btn-sm btn-default">
                <i class="glyphicon glyphicon-trash"></i>
              </a>
            </td>
          </tr>
        }
      </tbody>
    </table>
  </div>
}

As you can see from the above code, there is nothing out of the ordinary for this table. You use the Bootstrap table classes to help with styling the table. You loop through the collection of product data in the Products property of the TrainingProductViewModel class. Each time through the loop, you display the appropriate data from the Product class in each <td> of the table.

Create the Alternative Design

The AlternateTableSample page uses the appropriate Bootstrap panel CSS classes to create the alternative design shown in Figures 2 and 4. Below is the code in the AlternateTableSample.cshtml page.

@model AlternativeTable.TrainingProductViewModel
@{
  ViewBag.Title = "Alt. Table Sample 1";
}
<h2>Alt. Table Sample 1</h2>
@foreach (TrainingProduct item in Model.Products) {
  <div class="panel panel-primary">
    <div class="panel-heading">
      <h1 class="panel-title">@item.ProductName</h1>
    </div>
    <div class="panel-body">
      <div class="row">
        <div class="col-xs-4 hidden-sm hidden-md hidden-lg">
          Intro Date
        </div>
        <div class="col-xs-4 col-md-3 hidden-xs">
          Introduction Date
        </div>
        <div class="col-xs-8 col-md-9">
          @item.IntroductionDate.ToShortDateString()
        </div>
      </div>
      <div class="row">
        <div class="col-xs-4 col-md-3">
          Price
        </div>
        <div class="col-xs-8 col-md-9">
          @item.Price.ToString("c")
        </div>
      </div>
      <div class="row">
        <div class="col-xs-4 col-md-3">
          URL
        </div>
        <div class="col-xs-8 col-md-9">
          @item.Url
        </div>
      </div>
    </div>
    <div class="panel-footer">
      <div class="row">
        <div class="col-xs-12">
          <a href="#"
             title="Edit Product"
             class="btn btn-sm btn-default">
            <i class="glyphicon glyphicon-edit"></i>
          </a>
          <a href="#"
             title="Delete Product"
             class="btn btn-sm btn-default">
            <i class="glyphicon glyphicon-trash"></i>
          </a>
        </div>
      </div>
    </div>
  </div>
}

Let's look at each section of the above code to see how it was put together. The first thing you see is the loop through the Model.Products collection. Within this loop is where you build a complete Bootstrap panel. In the heading area of the panel is where you place the ProductName property. Within the panel body is where you create a row and two columns for each of the other properties you wish to display from the Product object.

Notice that I am changing the column widths I use depending on the size of the browser. For anything that is a medium resolution and above, (according to Bootstrap) I am using a col-md-3 for the first column and col-md-9 for the second column. However as soon as a mobile device is detected, use the size of col-xs-4. If you look at the Introduction Date field you also notice that the words used are changed also depending on the size of the browser. This is one of the great things about using Bootstrap, the ability to hide and display things using simple CSS classes.

The last difference in this code compared to the normal HTML table is I use two glyphs for the actions that the user can take. It can be sometimes hard to click on a hyperlink with your finger on a mobile device. They can even be hard to see sometimes on a mobile device. I find using large buttons with a graphic gives the user a nice big target to hit with their finger.

Summary

In this blog post, you were presented with a method to present data to the user that is different from a traditional HTML table. While you may not like the exact user interface presented here, hopefully this article will spur you to question your user interfaces a little more and come up with some alternate methods of displaying lists of data.

Sample Code

You can download the complete sample code at my website. http://www.pdsa.com/downloads. Choose "PDSA Blog", then "An Alternative to HTML Tables" from the drop-down.


Keep Your Software Up-To-Date

Yes, it is always a struggle to keep your software up-to-date, but it is vital that you do so. Microsoft and Apple upgrade their operating systems every couple of years. Sometimes, when they do this, they break compatibility with their older operating system (OS). While this might be fine for most software, sometimes it does cause older software running on the new OS to break. If you have older software such as software written using Visual Basic 6 or earlier, FoxPro, PowerBuilder, and others, this means you are at risk of your software no longer working.

So, you might be thinking that you can just require your customers to run on the older operating systems. This might work for a couple of years, but at some point, your customers are going to want to, or need to, upgrade to the new OS. In fact, they may have to as Microsoft and Apple no longer support the older OS. There can be very serious consequences for not upgrading such as security risks. In today’s world with identity theft on the rise, people need to take every precaution to keep their computers safe. Staying current on the new OS versions is one way to stay safe.

You have a lot of time and money invested in your old software, and rewriting it can be an extensive undertaking. However, when you look at the alternative that your software no longer works, and you can no longer run your business, or your customers no longer purchase your software, how much is that worth? Could your business fail because of old software? This could be a real possibility.

So, the time to be looking at updating your software to new versions of .NET or Java is now, not when it stops working on a new OS release. By the time it stops working, you might not have enough time to rewrite before all your customers move on and you are now out of business.

Fairway Technologies can assist you with the migration of your old software to the most up-to-date languages and platforms. Call us today for a free consultation and let us help guide you on your path to new software that will last for years to come.

8 Questions to Ask to Determine if you should be in the Cloud

Everyone wonders if they should be moving to the cloud. Here are 8 starter questions you should ask yourself. Are you...


  1. Spending too much time on your IT infrastructure?
  2. Anticipating future growth?
  3. Needing to react quickly to change?
  4. Tired of hassling with Microsoft Exchange?
  5. Wanting to run your software as a service?
  6. Constantly adding more hardware to run your company
  7. Worried that your servers may not be backed up properly?
  8. Concerned about disaster recovery?

If you answered "Yes" to even one of these questions, a cloud solution may be just what you need. Companies are successfully using the cloud to scale their applications up and down without purchasing more equipment for the organization. Moving your applications into the cloud offers multiple benefits including:

  • Better security
  • Less manpower needed to manage software updates
  • More flexibility in application management
  • Disaster recovery is easier

If any of these keep you up at night, you should consider moving into the cloud. Fairway Technologies can help you migrate your infrastructure and your software to the cloud. Read more in our special report entitled Why Move to the Cloud?

PDSA is now Fairway Technologies!

PDSA is now Fairway Technologies PDSA has merged with Fairway Technologies! This is definitely a case of one + one = three! When two great companies, that have made customer service a priority, come together, the end result is spectacular for our clients. With this merger, Fairway now has over 50 employees to help serve our customers in everything from Java to Oracle to SQL Server to .NET.

Stay tuned for more exciting news as we get our two companies completely integrated. In the meantime, it is business as usual at PDSA and at Fairway. All employees at PDSA and Fairway are very excited about our integration and will be sharing all resources to ensure a smooth transition.

Testing is Not Just for Quality Assurance People

Testing Every developer needs to test their code, or have it tested by someone. I don’t know about you, but I am horrible at testing my own code. Does this mean that I do not need to test my code? Heck, no! It is always best if you do not rely on your end-user to test your code. This can end up with a very frustrated user, and your user can lose faith in your ability to get their project done. There are several ways you can get your code tested. This article explores a few of these methods for testing and talk about the advantages and disadvantages of each.

Why you should Test your Code

We all know that we need to test our code prior to putting it into production. Testing is your way of ensuring that the code you have written actually works as expected. But it is not enough to check that it works as expected, but also under varying circumstances, and with different inputs. For example, what if someone takes the database offline? Will your code recover gracefully from this exception? Does your code inform the user that there is a problem with the database connection in a friendly, easily-understood manner? All of these questions should be answered in the testing of your code. You need to simulate these exceptions so you can test your exception code.

Performing the act of testing often helps you improve the quality of your code. As you think about the various scenarios that can go wrong, you add additional code to handle these scenarios. This leads to your code being more robust and ultimately more maintainable and user-friendly. You will find that taking time to test your code makes you a better programmer in the long run. Your boss, and your end-users, will appreciate the extra effort.

Problems with the Develop/Test Cycle

There are a lot of disconnects between the development of the code and testing of code. In many cases there is too much code embedded in the user interface (UI). Too much code in the UI makes testing hard because the tools for testing user interfaces aren’t very robust. It is also hard to determine if all of the code in the UI has actually been tested. A tester has to know all of the inputs to give the UI to have it run all of the code.

This leads to yet another disconnect; there is too much communication required between a developer and the QA person. Sometimes a developer will forget to tell the QA person about a “special” case. In other cases, a QA person forgets to tell the developer about something that failed, so it does not get caught and ends up as another bug that, hopefully, will be found later.

Another problem is when a developer thinks they have fixed a bug, only to find out that the fix caused a bug in another part of the program. The QA department may not know to test that other part of the program which could mean a bug gets shipped to a customer. Or, the QA department thinks it affects other areas, so they end up doing a lot more regression testing than maybe they need to.

How to Test Your Code

There are many different methods used to test code. Here are some different methods you can use to ensure you are writing quality code.

  • Use a Quality Assurance (QA) person or company
  • Have your end-user test
  • Have a co-worker test
  • Write code to test your code

Of the above listed methods of testing, the first three involve humans, while the last one is a more automated approach. Let’s look at these different methods of testing code.

The Human Approach

Having a human test your code does have a lot of advantages. First off a human is going to be able to click on different buttons and test the UI very well. Having different people test your code can be helpful because each person may think of different things to test. In addition it will take less time up front to develop your software. 

But just as there are advantages to using humans for testing, there are also disadvantages. Testers find bugs, document them and push them back to you to re-code. After this, the tester has to go back and re-test. You will find this takes a lot more time in the long run. Many times prior to testing someone has to create records in a database, and afterwards get rid of tables, records, or files on disk. This is a very time-consuming and error-prone operation. You also find that the burn-out rate for QA people is very high. You frequently have a high turnover rate in this job function. So there are many down-sides to using humans to perform testing.

The Automated Approach

Instead of having a human do all the testing, you should start to use the great testing tools that are available in Visual Studio to create automated tests. Unit testing has become very prevalent in today’s professional software shops. Unit testing simply means you write a program, or most likely a series of programs to test each line of code you write to ensure that it operates properly under all circumstances.

While this sounds like a lot of work, and it can be more work up-front, you will more than make up that time by avoiding multiple regression tests by a human. You can automate the setup and tear down of databases, files, etc. With the correct architecture you can automate almost all the various inputs a human tester would have to enter by hand.

You will also save the time you normally eat up when you do your own testing by pressing F5 to start Visual Studio, wait for the compile process, click through a half dozen menus to finally get to the point where you want to start testing. As you know, this can sometimes take 15 seconds to a minute depending on how large your application is. Instead, you can run one or two tests in just a couple of seconds. This will add up in saving you many hours over the complete development cycle.

As you can see, there are many advantages to an automated approach over a human approach to testing. Automated tests are repeatable as opposed to having a human who might forget to test something. You will end up with more of your code tested because things won’t be forgotten. Because you will be forced to think of how to test your code while you are writing it, you will write better code. You will also save time on the setup and the tear down of the tests since these tasks can also be automated.

Of course, there are disadvantages to the automated approach as well. First of all, it does take more time up-front to develop these tests. Automated tests are only as good as the person that develops the tests. The tools to test user interfaces are not too great at this time without spending a fortune on third party testing tools. Of course, if you are using good N-Tier techniques, MVC, MVP, MVVM or similar design patterns, there should be very little UI for you to test anyway. 

Which Approach Should You Use?

The big question is this: do you use automated unit tests or do use a QA department? I still think you need a little of both. You want to get as many automated tests as you possibly can as this will save a lot of regression testing. Then the QA department can focus more on system testing, workflow and ensuring the correct data is flowing all the way through the application. The QA department can also focus on the UI features that are difficult to automate. A good mix of the two will go a long way toward making your applications much more robust and error free.

Architecting Your Code for Testing

As you are coding your application there are things you can do to prepare to take advantage of unit testing. Correctly architecting an application will do wonders for re-usability, readability, upgradeability, maintainability and testability. Take advantage of the design patterns that exist today such as MVC, MVP, MVVM or derivatives thereof. All of these patterns help you remove code from the user interface layer of your application. Removing code from the UI layer is this is the single best thing you can do to have a well architected, easily testable application.

Your UI code should strive to just call or bind to classes. Each class you write is where all the logic is contained for your application. Moving all application logic into classes, you take advantage of the various unit testing tools in Visual Studio. All of these classes should be combined into assemblies to aid not only in testing, but also in re-usability. 

Other techniques you should employ are to make your methods as small as possible.  A method should do one thing and one thing only. This makes testing that method easy as you most likely will only need to write one method to test that method. It is better to have many smaller methods and smaller tests, than one large method with lots of tests against that one method. One last technique is to use code generation tools for generating your CRUD layer. Create, Read, Update and Delete logic is employed in almost all business applications and is very standard code. There is no reason to hand-write this code with all of the tools available today to generate it. And, generated code is generally code you do not need to test. If the code generator is good, it will generate bullet proof code every time.

Visual Studio Testing Tools

Beginning with Visual Studio 2008, unit testing tools were added to almost all SKUs of Visual Studio. This means you do not need to purchase Team Foundation Server to be able to use unit testing. It also means you do not have to use NUnit or some other third-party application for unit testing. It is available to you right out of the box. Of course, the TFS version of Visual Studio has many more features, but for basic unit testing, you will find everything you need in the normal versions.

Summary

Unit testing is something every developer should employ as a part of their software development life cycle. Not only will help you improve the quality of your code, it will save you time and money in the long run. As you focus on architecting your applications for unit testing, you will find that your code will become re-usable, maintainable and more robust. Take some time to learn about the unit testing tools built-in to the Visual Studio suite of products and you will be on your way to better productivity.


The Importance of a CIO

CIO Services Are you without a CIO in your company? Did you know that a good CIO can save you money and keep your projects on-time and on-budget. What are some of the key duties a CIO performs that helps a company achieve its goals?

IT Assessment

A continuous review of your business and IT organization to determine where they are aligned and where they are mismatched.

IT Roadmap

Lay out the future vision of where your IT organization needs to be in order to be aligned with your company's financial and strategic goals.

IT Executive Mentoring

Be the go-between the executive team and the IT team. Ensure that the projects being worked on are in alignment with what the business needs.

Application Lifecycle Management

Look at IT processes and personnel to identify areas where those processes might need a little more guidance. Provide a comprehensive guide to how all IT projects should be run.

More Information?

If you would like more information on how a CIO can help you visit our page here. Call us for a complimentary assessment and how our Virtual CIO service can assist your company keep your IT projects on-time and on-budget.

Everyone Needs Help Now and Then...

Professional MentoringYes, you can google for answers to tricky programming problems. However, when you get back 5 different answers, how do you know which one is the best one to use? This is where PDSA, Inc. comes in. We have over 270+ man years of development expertise among our developers. We use tried and true techniques every day in our consulting business to solve many of the same business programming problems that you are facing. When you engage with PDSA, you aren't just getting one expert, you are getting a whole company of experts. 

Unlike tech support from a company like Microsoft where you pay for help whether or not they solve your problem, with PDSA you only pay if we solve your problem. We also bill in 15 minute increments instead of for a whole hour. This will save you money, and most importantly, time. We have been successfully mentoring with many of our clients for years. They use us periodically as needed to answer their tough questions, or just to bounce ideas of us. However you choose to use us, know we have your best interests in mind. We have been around for over 25 years and we are proud of the fact that we have so many repeat customers. We are successful because we make you successful.

For more information on our mentoring services, visit our Mentoring page at http://www.pdsa.com/Mentoring.

Call us today at (714) 734-9792 and ask for Michael Krasowski or David Lefort. We will then get you in touch with one of our senior technicians that can assist you with your mentoring questions.

MVC, Web Forms, or Client-Side Technologies?

It seems like everywhere you read, everyone is talking about using Angular, Bootstrap, or MVC to create web applications. But what about programmers still working in Web Forms? You want to continue to use Web Forms and still build mobile web apps, use jQuery, Angular and Bootstrap. Not to fear, Web Forms is not dead, and nearly everything you can do in MVC, you can also do in Web Forms. Web Forms can also use client-side frameworks just as well as MVC.

MVC Advantages

Many programmers feel they have to choose one technology over another. But, there is really no reason you can’t program in both MVC and Web Forms and use each for what they are good at. Many MVC programmers give many reasons why you should use MVC as opposed to Web Forms. The reasons I hear more often are:

  1. Fine control over the HTML generated
  2. Ability to unit test
  3. Can control the "id" attribute generated
  4. Easier to use jQuery and JavaScript because no generated "id" attribute
  5. Ability to use Friendly URLs
  6. No ViewState sent to client

Web Forms Advantages

Of course, programmers that like Web Forms have many reasons why they want to stick with it:

  1. Rapid Application Development
  2. Less code to write because of rich server controls
  3. Lots of server controls to choose from
  4. Great third-party support
  5. Easy to preserve state
  6. They like the event driven model
  7. Hides the complexity of the web

Client-Side Advantages

Of course there are many advantages to using client-side code as well.

  1. Very fast
  2. Greatly reduces the need for post-backs
  3. No hiding of web behind any server-side technologies
  4. Lots of frameworks to help you develop

Which One to Choose?

Each of the technologies above has disadvantages as well. The best part is, you do not need to just choose one. You can have the majority of your web application written in Web Forms and still start using client-side technologies like jQuery and Angular. You can also start adding new pages in MVC and these can integrate with your Web Forms pages with no problems.

Almost all of the advantages outlined above for using MVC can also be accomplished in Web Forms as well. You might have to slightly modify the way you work in Web Forms, but it can be done. Both technologies use ASP.NET, so the engine is the same. If you wish to just stick with Web Forms, then do that. If you want to learn more about having Web Forms take advantage of MVC-like features, read my old blog post called Web Forms is Not Dead located at http://bit.ly/2ehCTP1.

Using Angular

Many Web Forms developers ask about Angular and using it in their Web Forms apps. The great thing about Angular is you can easily add it to your Web Forms or MVC application. You will most typically use Angular for new pages that you wish to create in your existing application, or to replace slow performing pages. This means you will probably start with a plain old HTML page and then add your Angular code to that.

Summary

It is up to you which technologies you are going to use when developing your web applications. Using ASP.NET Web Forms or MVC are both good choices and both can be made to run quickly or slowly depending on how you code it. Taking advantage of client-side technologies such as Angular and jQuery can give you a performance boost. If you need help with any migration or learning any of these technologies, please contact PDSA and we will be glad to help.

More Angular Routing Topics

In the last blog post (Introduction to Angular Routing) 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.

.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.
<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.
(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.
<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.
<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.
.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.
(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.
<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.
<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.
<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.
.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.
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:
.when('/page2/:id/:extraText',
{
  templateUrl: 'page2.template.html',
  controllerAs: 'page2',
  controller: 'Page2Controller'
})
In your index.html, you call this route using the following:
<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.
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.
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 as 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.

Sample Code

You can download the code for this sample at www.pdsa.com/downloads. Choose the category “PDSA Blog”, then locate the sample PDSA Blog Sample: More Angular Routing Topics.