Tag Archives: angularjs

Creating Multipage SPA’s with AngularJs and TypeScript

Ok in the last post we created a really simple “Hello World” application using AngularJS and TypeScript. This was probably the simplest of apps we could write but it did give us a chance to introduce a number of key concepts. I’ll list them here.

• AngularJs bootstrapping
• AngularJs data binding
• Setting up Webstorm for TypeScript dev
• Building a basic controller.

So that’s great but we want to go further than this. Often when we build applications in technologies such as Java or .Net we use a number of different libraries/apis. In the last post we pulled in one such library (AngularJS) but we didn’t actually need to use any of its api and instead relied on the declarative features. Now we will go beyond that and dip our toes into parts of the api.

What’s a SPA?

The buzz word this year is SPA’s or Single Page Applications. If you haven’t come across this term yet don’t worry as it’s still quite new and will become more prevalent over the course of the the next few years. First let’s clear up some confusion about what SPA means as I think it can lead to some confusion. Although your app is called an SPA and does run inside of a single html page, that doesn’t mean that you’re limited to a very simplistic UI or that everything must be shown on screen at the same point.

You should look as SPA’s as the same way you would look at WinForms or WPF application. The “Single Page” part of the acronym is really just your application container or host. When you come to build your app you will see that you can actually have 100’s of pages/screens in a SPA. In the same way you add a new page/form to a WPF application running on a user’s desktop, you will see we do exactly the same for our SPA apps.

Create our host page.

Before we get into the creation of multiple pages and routing in AngularJS let’s talk about the host page first. In traditional .net apps when you start them there are a number of things happening. Two of the most important however is the loading of your custom dependencies, normally dll’s you’re are using as well UI initialization where you may be loading a custom theme which will be applied to your app (app.xaml).

You normally load these things upfront because they are core to the application and are often required to be available before your application code starts running. The same is true for SPA’s therefore we need a host page which will do this work for us.  Lets take a look at a really simple host for our application.


<html ng-app="myApp">
<head>
    <title>Multi-page SPA - Typescript and Angular</title>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js" type="text/javascript"></script>
    <script src="app.js" type="text/javascript"></script>
</head>

<body>

<div>
   <div ng-view></div>
</div>

</body>
</html>

If we take a moment to dissect this html there are only a couple of things worth mentioning. First we are loading 3 dependencies into our app.

Bootstrap – An awesome CSS start kit from twitter which gives you out of the box theming for you application
• The AngularJS library
• app.js which is our application code.

The second is that we have an new AngularJs directive ng-view.

What’s ng-view?

If you look at the body of our page you will notice I’ve introduced a directive from the AngularJs framework called ng-view. The ng-view directive in angular is incredibly powerful. It works in conjunction with AngularJs’s routing provider and is used to inject fragments of HTML into the DOM where that directive has been applied. The best way I can think to describe this is to compare it to XAML construct, the ng-view directive being applied to the div essentially turns the div into a XAML’s content presenter control. So that’s our host page setup, I don’t need anything else for this demo in the host so lets move forward.

Enabling intellisense and type checking for AngularJs

As I mentioned the ng-view directive works in with Angulars routing provider in order to display content, but as it stands our application has no routes and we need to configure these for this to work. It’s now that we get a chance to play with the AngularJs api. As we are using TypeScript we can take advantage of one of its key selling points, the ability to pull in type definitions for any JavaScript library and provide us with full intellisense and type checking. These definitions are called ambient declarations and work similar to how c++ header files work.  There is actually a site which has many of the most popular definitions already defined for us, its called DefinitelyTyped 

I went to this site and downloaded the angular.d.ts file as well as jQuery and added it to my Webstorm project. NOTE: As d.ts files are purely definitions they do not get compiled into JavaScript which is why I do not need to reference the files in my host page. They are  there to support the tooling. 

For the sake of simplicity I only want to have a couple of pages in my app as I think this illustrates the concept well enough. I would like page1, page2 and then when the user attempts to navigate to a page that doesn’t exist I’d like to show them a 404. So I have just added these to my project under a folder called pages. You can see what my final project structure looks like here.

multi-spa-1

Defining our routes

We now have our app setup with all the files we need, the last thing we want to do is define our routes and enforce the behavior I’ve specified. Let’s jump to the app.ts file and write some code.


/// <reference path="includes/ts/angular.d.ts"/>

var app = angular.module("myApp", []);

//Set up our site routes
app.config(($routeProvider) => {
    $routeProvider
        .when('/page1',  <ng.Route>{ templateUrl: 'pages/page1.html' })
        .when('/page2', <ng.Route>{ templateUrl: 'pages/page2.html' })
        .when('/404',  <ng.Route>{ templateUrl: 'pages/404.html' })
        .otherwise( <ng.Route>{ redirectTo: '/404' });
})

Ok breaking this code down, you can see the very first thing we do is to instruct the TS compiler and tooling that we want to import all the type definitions for AngularJs. This is what gives us full intellisense and type checking around the api.


/// <reference path="includes/ts/angular.d.ts"/>

multi-spa-2
Next we define a new angular module. Angular modules are really a way for you to break your application into composable chunks. We will cover this in more depth in a future post, for now just note that the name of the module matches the one we defined in our html host. We will be able to configure this module in the next step.


var app = angular.module("myApp", []);

The final piece in the puzzle is the definition of the routes. Using the config object which hangs of our module we can inject a $routeProvider. Don’t worry about how this gets injected just yet as we will cover AngularJs’s injection in a future post, just trust in the fact that you will be given a $routeProvider and that it’s this object we will use to configure our routes.


//Set up our site routes
app.config(($routeProvider) => {
    $routeProvider
        .when('/page1',  <ng.Route>{ templateUrl: 'pages/page1.html' })
        .when('/page2', <ng.Route>{ templateUrl: 'pages/page2.html' })
        .when('/404',  <ng.Route>{ templateUrl: 'pages/404.html' })
        .otherwise( <ng.Route>{ redirectTo: '/404' });
})

In the configuration you can see it uses a fluent API to define routes, specifically it uses “when” to define the rules of route and where it should go. We setup three routes for our page1, 2 and then our 404. The final thing we do is use the “otherwise” method define the fall back when no route has been found that matches the rules. In our case the 404 page.
At that point we are good to go, if we run the app and try different urls like default.html#/page1 or default.html#/unknown we can see the route provider is doing its job and taking us where we want to go. Now behind the scenes AngularJs is doing a lot of the heavy lifting for us, firstly it is monitoring the location of the url and when that changes it checking the list of routes that have been defined in order to see if we there is a matching rule, then if it finds a matching rule is downloads the template from the server (no they are not eager loaded) then once downloaded the ng-view attribute that we had in our host is injecting the html fragment into the DOM. There is tonne of stuff I’m leaving out here but that’s the gist of it.

Summary

You can now see in a very simple demo how we can build multipage SPA’s. The ability to dynamically load a screen into your SPA gives you a very powerful composition model, as we explore more about the AngularJs api you will see many examples of how this and other types of composition can help us build very complex ui. You can grab the code for this demo here.

Advertisement

Getting started with AngularJs, TypeScript and Webstorm

I’ve been working with TypeScript since it was released and I have to say I love it. Over the course of the last 9 months I’ve learnt a lot about the language as well as using it within a number of IDE’s and with lots of libraries. At work we are currently building a very large AngularJS + TypeScript application for a front office environment. I plan to blog some of the things I have learnt during this time.

AngularJS is an MVC/MVVM SPA application framework from Google. The project is open source and comes with a number of powerful features to help kick start you applications. These include powerful data binding, a templating engine, dependency injection, routing and the ability to extend HTML with your own custom tags which works across browsers.

I believe that AngularJS is probably the best framework out there at the moment for building your SPA’s. I have tried knockout and ember etc but Angular seems to have the most familiar features that I am used to as a .net/xaml developer moving back into the web world. In fact I’d go so far as to say that the Angular boys have taken quite a few tips from the WPF model.

Lets create the HTML

For the purpose of this post I am going to focus on building a hello world application in Webstorm. I originally started TypeScript using Visual Studio 2012 but as time has progressed I have found I have transitioned JetBrains tools.

So first up, if you want to use TypeScript in Webstorm you’re going to need 6.0+, so go download it and once stared create a new empty project in the location of your choice. Next up lets create a really simple screen, the html below, what we want is an input field, a button and somewhere to display the text to the user. This shown below.


<!DOCTYPE html>
<html ng-app>
<head>
    <title>Hello World - Typescript and Angular</title>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js" type="text/javascript"></script>
    <script src="app.js" type="text/javascript"></script>
</head>

<body>

<div ng-controller="HelloWorldController">
    <div>
        <input type="text" ng-model="inputText" />
    </div>

    <div>
        <button ng-click="onDisplay()">Display me</button>
    </div>

    <div>
        <h1>{{displayText}}</h1>
    </div>
</div>

</body>
</html>

Ok everything is setup for us to get started, now first thing we want to do is pull in AngularJS. For the sake of this example I’m happy to use the cdn version which can be found here https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js.  After you have done this add a app.js to the head. We haven’t created this file yet but we will come back to that later.

Bootstrapping our app

AngularJs comes with a number of built extensions to html called directives which allow you to quickly build you app in a declarative way. The first directive we are going to look at is the ng-app directive. This attribute can be applied to your html tag and simply allows angular to know that there is an angular app in scope and that is should initialize itself.

If you run the app at this point you’ll see nothing happens, this because we haven’t actually written and code, as mentioned previously Angular uses an MVC pattern. Therefore to add behaviour to your app we are going to have to create a simple controller and bind it to the DOM somehow. To do this we use another angular directive called ng-controller. I’m not going to get into the details of the ng-controller directive right now but just know that it can be applied to any element and that descendants of this element will have access to a shared scope which the controller provides. We specify a controller name for the directive HelloWorldController. Angular will attempt to resolve this controller automatically when the app starts.

Data binding

The last things we need to do to our html page is to specify some data binding. If you’ve worked in WPF before you will find there are a lot of similarities. The Angular data binding engine is incredibly flexible, I’d say more so compared to wpf and implements a dirty checking algorithm for deciding when update the DOM. There is a great in depth post on stack overflow here.

In our little app we want to be able to capture the text that a user types into an input element. Normally in jquery we would have do some fancy event handling to manage all this however in Angular we have the ng-model directive which can do this nicely. This works by basically monitoring the changes to the input and when a change is received it updates the “scope” object to store the data.

Next we want display the result of the input value prefixed with “hello”. To achieve this we can use one of Angulars coolest features “expression binding”. Assume for the moment that our scope object (that we haven’t built yet) has a property called displayText. In order for us to inject that into the DOM all we need to do is use double curlies. {{displayText}}. I can’t stress how easy this is and also how much time you will save by not having to manually manipulate the DOM.

So now we are almost there, the last thing we want to do is add some behaviour to our display button so that when the use clicks the button the displayText is updated and shown to the user. To do this we have our final directive for this post ng-click. ng-click provides a commanding pattern so that we can invoked custom behavior easily. You can also bind to functions but that’s for another post.

The binding for ng-click is pretty simple, all we need to do is state what function we want to run when the button is clicked. Cool we’re all set……….LETS write the controller and make all this work.

Setting up Typescript compilation in Webstorm

It’s now time to get started with TypeScript, in Webstorm go to add a new file, you will see that typescript is now a supported option. Go ahead and add a app.ts file. At this point Webstorm will display a big green banner asking you if you would like to setup a file watcher to compile TS files in JS. Go ahead and click add watcher. Now it’s important to note here that you may not have TypeScript compiler installed on your machine. You can get the compiler a couple of ways, either download the installer from the TypeScriptLang site or run the node npm command to pull it down.  Once you have it on your machine just point Webstorm at that exe or bat file and Webstorm will do the rest.

Building our controller

As we mentioned previously we the ng-controller directive instructs angular to go look for a controller with the name we specified. So we can now build that controller in typescript. This class is really simple and should be self explanatory but what is important to note is that we are using TypeScript’s classes in order to provide our controller. Classes will be coming to JavaScript in ES6 but TypeScript allows us to use them now which is very cool. What is also very cool is that TypeScript classes get compiled into constructor functions which is exactly what AngularJS actually requires for its controllers. I’ve got the TypeScript code and the compiled JavaScript below for you to review.


class HelloWorldController{

    constructor(private $scope){

        $scope.prefixText = "Hello ";
        $scope.inputText = " ";
        $scope.displayText = "";
        $scope.onDisplay = () => {

            this.$scope.displayText = this.$scope.prefixText + this.$scope.inputText;
        };
    }
}


var HelloWorldController = (function () {
 function HelloWorldController($scope) {
 this.$scope = $scope;
 var _this = this;
 $scope.prefixText = "Hello ";
 $scope.inputText = " ";
 $scope.displayText = "";
 $scope.onDisplay = function () {
 _this.$scope.displayText = _this.$scope.prefixText + _this.$scope.inputText;
 };
 }
 return HelloWorldController;
})();

And with we are done, we have a simple “Hello World” SPA built in Typescript and AngularJs. You can grab the source for this post here.

In our next post we will look at how we can use the AngularJS API inside of TypeScript and get full intellisense support.