Introduction to Angular Routing

To build a Single-Page Application (SPA) using Angular (v1.x), you typically build a single HTML page and inject HTML fragments within this one page as the user navigates within your application. Navigation in Angular employs a mechanism called routing. This blog post explores how to perform navigation within a SPA using Angular routing.

Server-Side Development

As you make the transition from server-side development to client-side development, you will find many of the same concepts that you employ on the server-side have equivalents on the client-side. Of course, they are done differently, but the concepts are there nonetheless.

When developing server-side web applications with MVC or Web Forms, you use a common layout page for all of the standard “chrome” you want around your content. This chrome is your header, footer and maybe a sidebar. The header consists of a menu system and maybe some graphics. The footer might have a copyright and some additional links. You do not want to duplicate the header and footer on each page in your application as that is a maintenance nightmare. Instead, each MVC or Web Forms application has a special “layout” page where you create the chrome. You create your content pages with the HTML fragments you wish to display to the user, and inject those fragments within the layout page.

MVC has a special page named _Layout.cshtml located under the \Shared folder (Figure 1). This page has a piece of Razor code called @RenderBody() which tells MVC into where to inject your fragments of HTML and Razor code. Web Forms uses a concept called a “Master Page”, shown in Figure 2 as Site.Master, which uses a <asp:ContentPlaceHolder /> control to specify where to inject your content pages.

Both these approaches keep the chrome for your web application in a single location. This makes changes to your website easy to accomplish. When creating a SPA using Angular (or any other client-side framework), you should strive to use this same technique.


Figure 1: MVC uses a shared layout page



Figure 2: Web Forms uses a master page

Angular ng-view Directive

Angular has the same mechanism for defining a HTML page with the chrome, and a directive for specifying where to inject the HTML fragments that make up each content page. You typically create an index.html page with the chrome and a single <div> tag that uses the Angular directive ng-view (Figure 3). This directive is what is used to specify the location in which to inject the content pages.
It is important to note that only one instance of ng-view may be used in your Angular application. In other words, you cannot nest an ng-view within another ng-view. If you are using this approach correctly, you shouldn’t have to nest ng-view anyway.


Figure 3: Angular uses any html page for the chrome

Download Routing JavaScript File

In order to use Angular routing, download the angular-route.js file into your project. If you are using Visual Studio, you may use the NuGet Package Manager to search for and install the AngularJS.Route package. Or, open a browser and navigate to https://code.angularjs.org/1.5.8/ and download the angular.route.js file from there. Either way, once you download this script file you will want to reference it from your main HTML page. Be sure to place it after you have referenced the angular.js file as shown in the following code snippet.
<script src="scripts/angular.js"></script>
<script src="scripts/angular-route.js"></script>

Declare Your Intention to use Routing

The first step in any Angular application is to define a module that is the main entry point for your application. You typically define a module using the following code.
(function () {
  'use strict';
  angular.module('app', []);
})();
As you are going to be using routing in your Angular application, this is now a dependency that you need to tell Angular about. The second parameter to the module() is an array of strings for you to specify the names of any dependencies needed for your application. In the code snippet below you are passing in a single element array with the value being ‘ngRoute’. The ‘ngRoute’ value is defined as a provider in the angular-route.js file you downloaded and included in your project.
(function () {
  'use strict';
  angular.module('app', ['ngRoute']);
})();

The HTML Page

The complete HTML page, index.html, is shown in Listing 1. This page has a couple of anchor tags <a> that are used for our routing sample. In addition the <div ng-view> element is also defined within a Bootstrap row and column. This is where all HTML fragments will be displayed when you route to a new path.
<!doctype html>
<html>
<head>
  <title>Routing Sample</title>
  <link href="Content/bootstrap.min.css" 
        rel="stylesheet" />
</head>
<body>
  <div ng-app="app"
       ng-controller="IndexController as vm"
       class="container">
    <div class="row">
      <div class="col-sm-12">
        <a href="#/page1" 
           class="btn btn-primary">Page 1</a>
        <a href="#/page2" 
           class="btn btn-primary">Page 2</a>
      </div>
    </div>
    <br />
    <div class="row">
      <div class="col-sm-12">
        <div ng-view></div>
      </div>
    </div>
  </div>
  <script src="scripts/angular.js">
  </script>
  <script src="scripts/angular-route.js">
  </script>
  <script src="app.module.js"></script>
  <script src="index.controller.js">
  </script>
</body>
</html>
Listing 1: The HTML page for our routing sample

The index.controller.js file that is referenced in the above web page is an empty function as there is no functionality needed for this sample web page. The contents of the index.controller.js file is shown below just for completeness.
(function () {
  'use strict';
  
  angular.module('app')
   .controller('IndexController', 
               IndexController);
  function IndexController() {    
  }
})();

Define Your Routes

After you have told Angular that you are using routing, it is now time to create some routes. Within the app.module.js file (or create another file called index.route.js) add the code shown in Listing 2.
angular.module('app')
.config(function ($routeProvider) {
  $routeProvider
  .when('/',
  {
    template: ''
  })
  .when('/page1',
  {
    template: '<p>This is some text for Page1</p>'
  })
  .when('/page2',
  {
    template: '<h2>Page 2</h2>'
  });
});
Listing 2: Define routes to your Angular application.

The code in Listing 2 retrieves the module named 'app' from Angular. It then chains the config() function to instantiate the routes for the module. Pass in your custom function to the config() function. This function is passed the $routeProvider provider, which is defined in the angular-route.js file. You use this $routeProvider variable to define the routes you wish to configure using the when() function. Each when() function is passed two parameters. The first parameter is a string that is matched up with the path you define in your web page. For example, <a href="#/page1" …/> matches up with when('/page1'). The # symbol is used so the browser does not try to navigate to a page. Angular looks for anything that starts with “#/” and knows that you are using a route. Figure 4 shows the index.html page and the code in the $routeProvider definition and how they match up.


Figure 4: Use a # symbol to specify a route

The second parameter to the when() function is an Angular route object. This object has several properties that can be set. For this initial sample the template property is set. The template property lets you define any HTML code you wish to display in the ng-view directive when this route is invoked. In Figure 5 and Figure 6 you can see both the final web page and the corresponding code in the $routeProvider which caused that HTML to be displayed.


Figure 5: Page 1 shows some standard text


Figure 6: Page 2 shows some bold text

Handling a Bad Link

If you have a link in your HTML page that does not have a corresponding when() function configured, you should display some error text to your user. After the last when() function is called, add an otherwise() function as shown in the following code snippet.
.otherwise(
{
  template: '<h2>Bad Link!</h2>'
});

Avoid Hard-Coding HTML

The problem with the previous example is you hard-coded some HTML within your JavaScript. It is a best practice to keep all your HTML in .html files in your project. Instead of defining your routes using the template property, use the templateUrl property instead as shown in Listing 3. The templateUrl property must be set with the full path in relation to the index.html page. In this sample, all the .html pages are in the same folder. However, you might need to specify something like the following: templateUrl: 'app/templates/page1.template.html'.
angular.module('app')
.config(function ($routeProvider) {
  $routeProvider
  .when('/',
  {
    template: ''
  })
  .when('/page1',
  {
    templateUrl: 'page1.template.html'
  })
  .when('/page2',
  {
    templateUrl: 'page2.template.html'
  })
  .when('/error',
  {
    templateUrl: 'badlink.template.html'
  })
  .otherwise(
  {
    redirectTo: '/error'
  });
});
Listing 3: Use the templateUrl property to keep HTML code in .html files

In Listing 3 another new property was introduced in the otherwise() function, redirectTo. The redirectTo property allows you to redirect to another route. This property is most typically used in the otherwise() function. In the sample in Listing 3 if you attempted to go to a href such as the one shown in the following code snippet, you would be redirected to the path /error, which would then display the HTML in the badlink.template.html file.
<a href="#/badLink" 
   class="btn btn-primary">
     Bad Link
</a>
Another option for the otherwise() function is to simply specify a string as the first parameter. If a string is specified instead of an object, it interprets the string as a redirect to.
.otherwise('/error')

Summary

In this blog post you learned the basics of routing in Angular. Just like server-side web development, the concept of having a single place for all your chrome is also present client-side. The ng-view directive is used to specify where in your HTML page you wish to display other HTML pages. You will need to download angular-route.js in order to use routing in your Angular web pages.

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: Introduction to Angular Routing.

If You Fail to Plan, You Plan to Fail

IT Plan If you do not have a set of guidelines, templates and documents which describe and assist you in the many phases of a software project and the many challenges of running an IT organization then what are you doing in IT management? You must have these items in place in your IT organization in order to run a lean, efficient, on-time and on-budget shop. There are several items you must have in order to have a successful development team.

  • Application Lifecycle Management
  • Architectural Guidance
  • Management and Human Resource Practices

Check out our special report and see the kinds of guidelines, templates and documents you must have for each of the above items.

You Should be Using Bootstrap

Bootstrap Most users are browsing your website using a mobile device. Does your website look good? If not, then you should consider using Bootstrap for your CSS.

What is Bootstrap?

Bootstrap is a set of CSS and jQuery that helps you create responsive web pages. Responsive means that the styles of your website change depending on the device the user is browsing it from. This keeps your website looking good regardless of how the user browses to it.

How Does it Work?

Bootstrap's CSS changes on the fly based on the size of the browser. It uses what are called Media Queries which are a part of the CSS standard. A media query reads meta-data from the browser, then changes the styles to something that works based on the height, width or other browser information. For example, on a large desktop browser, a user might see columns of data across the page. However, on a mobile browsers, the user would see that same data, but going down the page. There is no additional coding your programmer has to do, this is all done just by using the appropriate Bootstrap styles.

How To Get Started

To ensure your website is responsive, you need a programmer or web designer that is familiar with Bootstrap. That person will make appropriate changes to each individual page to ensure it looks good on all types of different browsers. Yes, this will take time, but the end result is well worth the time and expense.

PDSA Can Help

Here at PDSA we have been using Bootstrap since the first version. We have successfully created many responsive websites for our clients. Contact us today for a complimentary analysis and proposal on ensuring your website can be viewed from all of today's mobile devices. Call us at (714) 734-9792 and ask for David Lefort or Michael Krasowski.

Generate Better Code, Faster!

Code Generation Are you or your developers writing stored procedures by hand? Are they creating duplicate CRUD (Create Read Update Delete) logic in multiple places? If so, you should consider a code generator.

Advantages of using a Code Generator

The benefits of using a code generator, such as the PDSA Haystack Code Generator to generate your data access logic are huge! If you are not using one, you need to ask yourself why? If the answer is because you think no one else can write code the way you can, that is not a good enough reason. When you consider how long it takes you to create, test and debug data access code, and how much time you put in when the schema of a table changes, you will soon find out that you are wasting a lot of time. The major reasons for using code generation are as follows:

  • Generation of INSERT, UPDATE and DELETE statements
  • Generation of stored procedures to do INSERT, UPDATE and DELETE
  • Bullet proof code for doing the Create, Read, Update, Delete (CRUD) logic
  • Ability to regenerate CRUD classes if schema changes
  • Consistency of code from one application to another
  • Moves SQL out of the UI tier and into a middle tier where it belongs
  • Moves the dependence on a particular database provider out of the UI
  • Reduces code complexity in the UI layer
  • Ability to map columns to properties in a class
  • Provide IntelliSense of tables, stored procedures, views and columns
  • Provides strong-typing of data in one location
  • Ability to customize templates to fit "your" style
  • Abstracts and encapsulates all data access code
  • Ability to separate programmers working on UI and data access

How to Pick a Code Generator

Before you start using a code generator you need to find one that allows you to do all of the things listed above. Be sure you can quickly and easily modify the code that is generated. In addition looks for one that supports generating multiple UI layers such as WPF, Angular, MVC, etc. The ability to generate a SOA layer such as Web API calls or WCF is an added bonus. 

Summary

How you create your CRUD logic needs to be thought out just as much as how you design the rest of your application architecture. Making many small classes/methods and then combining those together produces much more robust and maintainable code. Sure you end up with more classes, but these can be move to other assemblies so you don’t have to see all those files. You will definitely benefit in the long run. Using a code generator can really help speed up the development and ensure quality when developing the CRUD logic for your database application.

There are several code generators available for you to use. PDSA has the Haystack Code Generator (www.pdsa.com/haystack). The Haystack Code Generator does support all of the items listed above including the ones listed in how to pick a code generator.

Visit www.pdsa.com/haystack to learn more about Haystack and to download a free trial version.

Click here to read a special report on what code generation can do for you.

The Importance of a Chief Technology Officer

Virtual CTO Have you ever wondered if you and your team are creating applications in the most efficient manner? Would you like to be able to use the newest technologies, but don't know how to get there? If you answered yes to either of these questions, then it might be time to have a process and architecture review. What better person to perform that review than a professional Chief Technology Officer (CTO). PDSA has the right expert to help your team create a roadmap to move from point A to point B.

In IT, we need to keep our team growing, keep our processes up-to-date, and continue to use newer technology. All of this can be done while still getting your day-to-day jobs finished. Having a good technology roadmap in place, and getting senior management to buy in to that roadmap is essential. This roadmap covers both the process by which you develop software and your software architecture. If you are lacking such a roadmap in your organization, then it is hard to get senior management let you work on learning new technology and implementing that in your applications. The result of this is your development team feels antiquated, and if you are not careful, they will start looking for another job where they can be challenged and allowed to work with new technologies. If they do leave, you are left with downtime while you bring new people up-to-speed on your applications. In the long run this costs you way more than spending a little bit of time learning new technologies.

The job of a CTO is to assess the new technologies to determine which ones fit best in your software architecture. The CTO comes up with a roadmap on how to best learn and apply these new technologies. In addition, the CTO presents the plan to both developers and senior management to get a buy in from each. Finally, the implementation details are laid out and implemented. The end result is keeping management happy by the IT department delivering business value, and keeping the developers happy by learning new technologies. A win-win for all concerned.

PDSA can help you via our Virtual CTO program. We work with you to set a budget you can live with, and to meet the goals described in this blog post. Call us today at (714) 734-9792 and ask for Michael Krasowski or Paul D. Sheriff. We are happy to give you a complimentary assessment of your needs, and provide you with a proposal for our services.

Duplicate Data Entry Wastes Time

Software Integration Have you purchased a lot of off-the-shelf software? Do you use a few different cloud systems? Would you like to eliminate duplicate data entry? Would you like roll-up-reports across all of these different systems? If you answered yes to any of these questions, then PDSA can help you.

We have successfully integrated hundreds of systems over the years. Most cloud systems have an API layer that we can take advantage of to enter data programmatically, or extract data for you. We can take the data from one system and automatically post them to your other systems. This will save you a lot of time and money. Your employees will be much happier too as they won't get bored entering the same data over and over.

Call for Complimentary Assessment

Contact us at (888) 899-7372 or (714) 734-9795 and ask for Paul Sheriff or Michael Krasowski and we will give you a complimentary assessment of how we can integrate your software packages.

Is Your IT Organization Adding Value To Your Business?

Organizational Assessment Does your IT organization have a Application Lifecycle Management (ALM) process written down and is it actually followed? How well are your processes working for your team? Are you delivering business value to your company? If you answered no to any of these questions, it is time for an IT Organizational Assessment.

There are over 9 areas that it is very important to look at to determine whether or not your IT organization is adding value to your company, or if it is just a cost center. You should look at how you take in work, how projects are developed and implemented, and how your organization is structured. All of these areas, and many more, should be part of a formal assessment process.

An assessment needs to capture the "as-is", what you want as the "future state" of your organization, and finally a well-defined "road map" of how you are going to get to that future state. It takes a seasoned professional to perform this assessment and guide your organization through the transistion. PDSA has the expert guides to assist you with this process. Our professional IT Organizational Assessment presents you with a set of findings, reasons, recommendations and remediation steps. We are here to assist you and your team become the best IT organization and add true value to your business. Contact PDSA, Inc. today to schedule a complimentary consultation where we can outline how we can assist your organization.

5 Reasons Why You Should Not Be Running Your Business With Excel

Spreadsheet Problems Many businesses overuse Excel in the operation of their company. This can be a big problem and should be avoided if possible. If you turn these spreadsheets into a web application you make it easier to keep your business running efficiently. Do you know the 5 major problems with running your business on Excel spreadsheets?

  1. Sharing spreadsheets leads to outdated information
  2. Can't guarantee someone won't accidentally delete an important number or formula
  3. Someone uses the spreadsheet incorrectly resulting in inaccurate results
  4. Hard to share among multiple offices
  5. Intellectual property in a spreadsheet can walk out your door

Call us today for a complimentary assessment of your Excel spreadsheets and see if it makes sense to convert them to a web application. Call Michael Krasowski at (714) 734-9792.

The Journey from MVC to Angular

MVC to Angular Paul Sheriff has just released an exciting new course called The Journey from MVC to Angular. Check it out at http://bit.ly/2a3wVNU

Do you want to learn how to move from MVC step-by-step to AngularJS? This course will show you how to do just that. Learn to slowly replace your Razor code with client-side code that is much more efficient. Moving to client-side can give you incredible performance gains on your web pages. If you have ever wanted to learn this exciting technology, now is the time with this new course.

Head on over to Pluralsight, sign up, and start watching the course today!

PDSA Signs Training Agreement with Major Aerospace Firm

Professional Development PDSA signs training agreement with a major aerospace firm. PDSA will conduct training courses for several programmers in OOP and WPF. We will assist them with moving some of their older technology into current state-of-the art WPF applications.

PDSA has assisted hundreds of companies and thousands of developers over the years to grow professionally. We use webcasts, seminars, workshops, conferences, mentoring, video, and on-site training courses. We focus on real-world solutions in our training so you leave knowing how to build solutions for your company. For more information visit http://bit.ly/2a7UQLw.