Angular in a Windows Store app – Servicing


Today I’m adding an AngularJS service to the Windows Store project in Visual Studio. This service is making a call to an external webservice which returns some JSON data. This controller uses a promise to handle the call to the service and when it’s fulfilled the data is shown on the screen.

You can find the code:

WinJS Classes and Namespaces


WinJS provides you with a way to create namespaces and work with classes in your code. It provides functionality to create derivatives of your classes and combine them using mixins.

Class and Namespace

There are many frameworks that give JavaScript the feeling of working with OO. So does WinJS. WinJS uses the WinJS.Class.define function to define a class. The function takes 3 parameters. The first parameter is a constructor that is called when the object is instantiated. You can provide parameters to the constructor that can be used when instantiating the object. For example, in the code below a ‘name’ can be provided to the constructor of the ‘Human’ class. If your class doesn’t need a constructor, you can provide an empty function or use ‘null’ (which tells WinJS to create an empty function).

Often your class needs to do a little bit more than just being constructed. After providing the WinJS.Class.define function a constructor, you can give it an object containing functions or fields for the class to work with. These will be available when the class is instantiated. In the example below I added a function called ‘sayHello’ which uses the ‘name’ variable created in the constructor and displays it in a message.

Optionally you can add a third parameter to the constructor which will define static fields and functions. These can be called before the class is instantiated.

In a larger application you probably wrap you code in functions to create scope. In these cases you want your classes to be separated into different files, but possibly available to others too. That’s when Namespaces become handy. You might know namespaces from other languages like C#. They are easy to define with WinJS. Just make a call to the WinJS.Namespace.define function giving it the name of your namespace and an object with the classes. If the namespace already exists, the new members are added to it. In the example I added the ‘Human’ class to the ‘Species’ namespace. I also wrapped the code defining the class and the namespace in a function to create a scope around it. You can try for yourself and see what happens if you try to instantiate the ‘Human’ class without the namespace.


One of the powerful features of Object Oriented programming is Inheritance, with which you can reuse classes by deriving functionality from one to the next. WinJS provides functionality to achieve this in JavaScript. To create a derivative of a class you can use the WinJS.Class.derive function. The function is very similar to the define function described earlier. It takes one extra parameter, the class you want to derive from. It also takes a function as a constructor, an object with instance fields and an optional object with static fields and functions. I extended the previous example a bit and added the new derived class, ‘SuperHuman’. I gave the constructor of this class a second parameter and a new function. Then I added it to the ‘Species’ namespace. At the end you can see the instantiation of the object and calling of the two functions. In the Result window you can see the result of these functions.


Other than languages like C#, WinJS can add multiple inheritance to your applications. This means you can have your class inherit from more than one class and reuse code in more different ways. Creating a mixin is not complicated. In the example below I added an object ‘Job’ with a field and a function. By calling the WinJS.Class.mix function with both the original class, ‘Human’ and the new ‘Job’ object, you can have WinJS mix the two together. And thus use the ‘job’ field and the ‘work’ function from ‘Human’ class. Which is inherited by the ‘SuperHuman’ class, giving that access to these too. There are many ways in which this can be useful when using this in your projects.

WinJS provides a couple of handy mixins for you to use in your project. The WinJS.Utilities.eventMixin and the WinJS.Utilities.DOMEventMixin add event functionality your class. I’ve demonstrated the WinJS.Utilities.eventMixin mixin in the example below. One of the things this mixin adds to your class is the addEventListener function and the dispatchEvent function. To make an event work you also have to mix in the WinJS.Utilities.createEventProperties mixin. In the example below I used this to create the ‘laugh’ event. At the end of the example I added the eventlistener and called the ‘tickle’ function on ‘Superman’ to have it fire the event.


Please use the jsfiddles to experiment with the different functions and use them to create classes of your own. I hope the use of the fiddles helps explaining these functions of WinJS a bit. Please let me know if they do, or if I never should use these again in case they don’t :)

Subscribe to the RSS feed or follow me on Twitter. I also added links to my FlipBoard magazines to the left sidebar of my blog.

Angular in a Windows Store app

Angular JS

I was trying to use Angular JS in a Windows store app and had some issues with Angular being “unsafe”.

Using Angular JS in a JavaScript Windows Store app turned out to be pretty easy. Here’s how to do it:

First create a new app.

Install Angular JS though NuGet.

Add a scripts tag to your default.html.

<script src="Scripts/angular.js"></script>

Running the app at this point will result in the following error:

The trick to get around this error is to enable CSP (Content Security Policy) and the most convenient part is that Angular has a directive to set that. All you have to do is add the “ng-csp” attribute to your html tag.

Which results in:

<!DOCTYPE html>
<html ng-csp ng-app>
    <meta charset="utf-8" />

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.2.0/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.2.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.2.0/js/ui.js"></script>

    <script src="Scripts/angular.js"></script>

    <!-- AngularDemo1 references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>

And that’s it. If you run this, your app should print “10”. Getting WinJS to work with Angular is a whole other story… which I’ll explain in a separate post…

Additional note:

In order to get ng-cloak and ng-show to work property you’ll have to add some styles to you project. These style would be added dynamically in other situations, but because ng-csp is used this is disabled. This is the CSS, which can be found at the end of ‘angular.js’ (I removed a few unsupported):

<style type="text/css">
    @charset "UTF-8";

    [ng-cloak], [data-ng-cloak], [x-ng-cloak],
    .ng-cloak, .x-ng-cloak, .ng-hide:not(.ng-animate) {
        display: none !important;


List item delay in Pivot

In one of my apps I wanted to have the items in a list with the list being in a Pivot control. I wanted to have the items slide in with a little delay, like they are in the Windows Phone mail app. I’ve been looking for that a lot, but couldn’t find anything. Until I stumbled upon the Pivot Control Sample app. The actual solution is demonstrated in this sample. It doesn’t seem to be documented anywhere else…

Here’s how it’s done…

All you have to do to get the delay on the items, or basically any HTML inside the pivot items, is just adding one of three CSS classes: win-pivot-slide1, win-pivot-slide2, win-pivot-slide3. Where the first has the shortest delay and the last the longest.

To see the effect you can alter the “Pivot App (Windows Phone)” template app a little. Just create a new app using that template.

Then, open one of the pages. Section3Page.html for example and change the itemTemplate part of that HTML to:

<div class="itemTemplate"
    <div class="templatecontainer">
        <img class="win-pivot-slide1"
             data-win-bind="src: backgroundImage; alt: title" />
        <div class="itemcontainer">
            <div class="itemtitle label-extralarge win-pivot-slide2"
                 data-win-bind="textContent: title"></div>
            <div class="label-mediummid win-pivot-slide3"
                 data-win-res="{ textContent: 'Section3Description' }"
                 style="height: 82px;"></div>


And that’s it J


Detecting Phone, Desktop or Web with WinJS

I’m my previous post I showed how you can add a website to a universal project and share some JavaScript between all three. This is nice, but I will run into a situation where you’ll have some code that is not supposed to run on one of the platforms. In the C# world you can use compiler directives in situations like this. In JavaScript this is not possible (Although you could create constructions that mimic directives using Grunt for example). WinJS has some functionality build in that can help finding out what platform you are using.

There are two properties on the utilities in WinJS you’ll need:

Here’s a small example of you could use it:

if (WinJS.Utilities.isPhone) {
} else {
    if (WinJS.Utilities.hasWinRT) {
    } else {

Adding ASP.NET to your universal JavaScript Store apps project

While exploring the possibilities of using frameworks like KnockoutJS and Backbone in my store apps I started wondering if it would be possible to share my JavaScript code between Windows Store app, Windows Phone app and an ASP.NET website. After some exploration and fiddling with various options I figured it out.

Here’s how to do it.

If you have a solution with an ASP.NET website, add a universal project to the solution. Or add a MVC project to the solution with you universal projects.

Unload the web application and add to the following line to the file right before the import of “Microsoft.CSharp.targets”. Where App79 would be the name of your shared project of course…

 <Import Project="..\App79.Shared\App79.Shared.projitems" Label="Shared" />

This will enable the connection between the projects. Because linking JavaScript files doesn’t work in web projects (the files are not really in the expected folder) the files have to be copied too.

After some searching I came across the following blogpost by Matt Perdeck, Copying linked content files at each build using MSBuild. He explains how to have the build copy linked files to their target location.

By adding the following lines to the end of the project file, right before the last closing tag, files are copied before the build. He even optimized it a bit, by skipping the unchanged files.

<Target Name="CopyLinkedContentFiles" BeforeTargets="Build">
    <Copy SourceFiles="%(Content.Identity)" 
          Condition="'%(Content.Link)' != ''" />

Close the project file and reload the project. As you can see in the references section the shared project is included.

You need to make sure that the names of the folders in the shared project are available in the web project too. I assume these are already created in the Windows Phone and Windows Store projects.

One nice extra is that you can add breakpoints in the shared project that will hit when running the web project. You can also switch the context to the web application in the .js files.



WinJS Promises

For a while now I wanted to dive a little deeper into Promises, so I decided to write this tutorial.

For this tutorial I used the WinJS version as available on GitHub. If you want to follow along you’ll have to compile the code yourself. Which is very easy, but if you have any issues or questions please let me know and I’ll do a tutorial on that.

What’s a “promise”?

A promise is an object representing a value that is eventually returned by an operation. This object can be passed around like any other object.

Various frameworks have various implementations of promises. Promises are specified in the CommonJS Promises/A proposal. jQuery for examples uses Deferred. WinJS has its own implementation, but they basically work the same. You do something, and specify what happens then and then, until you are done.

The promise object has two functions you’ll use very often.

  • Then() à Allows you to specify what needs to be done when the promise is fulfilled. It also allows you to specify what to do when an error occurs and provide notifications on the progress.
  • Done()à Is almost similar to then, except it returns undefined instead of a promise. It is meant to be used at the end of the promise chain. It takes the same parameters, although unhandled exceptions need to be handled outside the promise chain and won’t be handled inside.

You will use the constructor a lot too. This can wrap some code in a promise and lets you handle the moment it is fulfilled.

Use a promise

One very common use of a promise in WinJS is its xhr() function. This function wraps the XMLHttpRequest in a promise and is used to make ajax calls. When given a URL and a response type the xhr() function returns a promise that is fulfilled when the call is completed, either by returning the data requested or when I fails and returns an error.

Let’s have a look at some code.

// create request object 
var request = 

//call to xhr
        var response = JSON.parse(r.response);

On lines 2 through 6 I create a request object. In this case I’m going to make a call to the YouTube API to request the playlists for a specific user. I specify I’d like the response to be JSON, both in the URL to YouTube and in the response type.

On line 9 I use the request object as a parameter in the xhr function. This function will make the call and returns a promise.

On line 10 the returned promise used immediately and its then function is called. As a parameter the then function takes up to three parameters, all three functions. The first, which is called when the promise is fulfilled successfully. The second parameter is a function the will be called when an error occurs. This allows you to handle the error and have the chain continue. The third function that can be passed to the promise function is used to handle the progress. Promises are not required to use progress.

Lines 11 and 12 parse the response and log the title of the first playlist to the console.

A more interesting situation

The service called in the previous examples returns the playlists for the specified user. But, say we want to know more about all these playlists. We’ll have to iterate over the lists of the playlists returned and make a new call for each playlists. When this is done we need to handle the results.

Promises are a big help in cases like this. Because promises are just objects we can create arrays of them. And the promise type has a function to join an array of promises to be handled as one.

Let’s change to code to the following:

        var response = JSON.parse(r.response),
            promises = [];
        for (var i = 0; i < response.feed.entry.length; i++) {
        return WinJS.Promise.join(promises);
        var playlistResult = [];
        for (var i = 0; i < x.length; i++) {
            var response = JSON.parse(x[i].response);
                    title: response.entry.title.$t,
                    summary: response.entry.summary.$t,
            return playlistResult;
        }, function(err){
        //do something with results from r[]

The request object used as parameter in the xhr function on line 1 is the same object used in the previous sample.

Line 5 through 10 loop over the entries returned from YouTube. Per entry a new promise is instantiated (line 6) and added to the promises array.

The real magic happens on line 11. On this line the complete array of promises is joined into one and returned. After this, the next then function is called when all these promises are fulfilled. An array with results, one item per request, is passed to it.

Inside the then on line 13 I loop over this results, parse them and add them as a new object into an array if playlist results. At the end of the function at line 23 I return this array so it can be processed further into another then or done.

I also added a handler for the errors on line 24. This way I know when something went wrong here.

One major downside to this technique is that the whole chain fails whenever one promise returns an error.

Custom promises

Often you have to work with 3rd party libraries that don't use these promises. Wrapping existing code into a new promise.

First, let's look at same code again. This code replaces the last then of the previous sample.

    return new WinJS.Promise(function(complete, error){

The constructor of the promise on line 2 takes a function with 2 parameters. The promise uses these functions to keep the chain going. Both parameters are functions that you can call from your code. In this example I use call magic function of some random library. This function takes an object which has a callback and an error function. When magic call its callback function, I call the complete function that was given to me by the promise. This will trigger the next step in the chain of promises and call the then or done function if it is specified. The value passed to the complete function will be passed to the then or done functions. In case of an error occurring magic calls what I specified on line 8. I just call the error function that was provided to me, passing it the error. This way it can be handled somewhere else.

Wrap up

I hope I shed some light on these promises. Keep in mind that code like this can be refactored pretty easily into multiple methods, because promises can be passed around in variables and parameters.

A complete version of source is available on GitHub.

Windows Store app with TypeScript and Knockout

Demo application

In this tutorial we’re going to make a very simple Windows Store app that uses TypeScript. The app is going to use Knockout to handle user input to search patterns on I assume you have read my previous tutorial on how to set up TypeScript compilation in a Windows Store app. We’ll start with an empty project after adding TypeScript compilation.


First we’ll start by adding our dependencies through NuGet. We have a dependency on KnockoutJS, because this is what we need for our bindings. To make the request to colourlovers we are going to use jQuery. First install both by searching them in the NuGet explorer, or type the following two commands in the NuGet console.

Install-Package knockoutjs
Install-Package jQuery

To make our lives a lot easier we are also going to install a couple of type definitions. There’s an awesome project going on over at GitHub, DefinitelyTyped. This collection contains definitions for many JavaScript frameworks and libraries. If you are using any third party library in your project you should definitely have a look at that.

For our convenience these definitions are available through NuGet also.

Install-Package jquery.TypeScript.DefinitelyTyped
Install-Package knockout.TypeScript.DefinitelyTyped

There are two definitions which we need also. There’s are for the WinRT and WinJS libraries used in the project. Although a version of these files come with TypeScript, the version on DefinitelyTyped are far more up to date. If you install the definition for WinJS, WinRT is also installed.

Install-Package winjs.TypeScript.DefinitelyTyped

That’s all for the packages. A small last trick. You can search by tag when looking for NuGet packages in the Package Manager, by starting your search with “tag:”. To search for anything on TypeScript, just search for “tag:typescript”.


Packages alone won’t bring us very far. Start by deleting the old default.js file and adding a new default.ts file. Add the code below to the file:

/// <reference path="../scripts/typings/winjs/winjs.d.ts" />
/// <reference path="../scripts/typings/knockout/knockout.d.ts" />

module Default {
    "use strict";

    WinJS.Application.onactivated = (args: any) => {
        if (args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
                    (rootElement) => {
                        // apply knockout binding …


The first two lines, in comments tell TypeScript to use these definitions as references. We create a module named Default. This code is pretty much the same as its JavaScript counterpart, except for the then on line 10. The function inside is called when the processing of the UI is done. This will be the place where we’re going to apply the knockout binding and create a new instance of our view model.

Knockout ViewModel

In this example we only need one view model. To create this, start by adding a new TypeScript file to the scripts folder. Add the following code to the new file.

/// <reference path="../scripts/typings/knockout/knockout.d.ts" />

module ColourLovers {

    export class PatternsViewModel {

        constructor() {


This code will be the basic outline of the view model. It starts by adding a reference to knockout, it than defines the module with the PatternsViewModel.

The class needs a property to store the query to use when calling the ColourLovers api. Add this piece of code to line 6:

query: KnockoutObservable<string> = ko.observable<string>();

This will add the query variable to the class and uses the generic type KnockoutObservable of type string. It’s that initialized immediately using the generic function observable on ko from Knockout. The use of this generic give you a great advantage over the JavaScript version. In JavaScript there’s no one stopping you for putting a number in there. This might cause problems on some occasions. TypeScript will give you an error, and in Visual Studio you’ll get a compiler error preventing you from running the broken code.

We also need a function to call whenever this value changes. At the following code between lines 9 and 10:

private search = function (value?){          


This function will only be used inside the class, thus it can be made private. Note that the private indication is only enforced by TypeScript. Because this function will also be called from the constructor, but without the parameter, it is nullable.

Speaking of which… Let’s implement the constructor and have it call the search function. The code on line 3 comes with Knockout. Whenever an observable changes its value, the subscribe function is call and the new value is passed to as a parameter. In this case it’s the value to search for on ColourLovers. We’ll just pass it on the search function.

constructor() {
    this.query.subscribe((value) => {;

The last thing to do in the view model is making the call to ColourLovers. This will be done in the search function.

private search = function (value?) {
    $.getJSON("" + value).then(
        (result) => {

The code for the search function is pretty straight forward. All it does is making an Ajax call and then it uses a promise (the jQuery version in this case) to handle the result. I’m using the lambda version of a function in this case. You could write the search function on line 1 as a lambda also, but I prefer “regular” function to be written as such and callback as lambdas as this keeps the code a bit more readable.

The result is placed in the result variable. We’ll have to define this also. It’s just one single line to add right below the definition of the query variable we defined earlier. For now, we make de observable array of type any so we can add anything to that.

result: KnockoutObservableArray<any> = ko.observableArray<any>();

To kick off the databinding with knockout you’ll have to call its applyBindings function. To do that, place the line below in default.ts inside the lambda.

ko.applyBindings(new ColourLovers.PatternsViewModel(), rootElement);

You should be able to run the code now, although nothing will be shown on screen. But, if you place a breakpoint inside the result of the search function you should be able to hit that and see the result.

The View

The view is build using two parts. The header, which contains a title and the searchbox. And the contents that contains a list. The connection between the HTML and Knockout is made though the data-bind attributes.

<div class="header">
    <h1>TypeScript HTML App</h1>
        <input placeholder="search" data-bind="value:query" />

<div class="patternsOuter">
    <ul class="patternsList" data-bind="foreach:result">
        <li class="patternsListItems">
                <img data-bind="attr:{src:imageUrl, alt:title}" />
            <div data-bind="text:title"></div>


To get a little formatting use the following CSS:

body {
    display: -ms-grid;
    -ms-grid-rows: 150px 1fr;
    -ms-grid-columns: 1fr;   
.patternsListItems {
    list-style-type: none;
    padding-bottom: 24px;
    padding-right: 24px;
.patternsList {
    display: -ms-flexbox;
    flex-flow: wrap; 
.patternsOuter {    
     overflow-y: scroll;    
     -ms-grid-row: 2;
.header {
    margin-left: 40px;
    -ms-grid-column: 1;

The data-bind on line 4 of the html binds the query property to the value of the textbox. Because it is two-way whenever the value changes the code is updated and the subscribe method is called on the view model.

The second data-bind is a foreach on the result property which is filled with the results of the query when the ajax call to ColourLovers is done. Everything inside the HTML-tag the foreach handler is on will be repeated for every item. This creates a list of <li/> with an image and a title.

Try running the code again. The application should work as expected now.

WinJS through helper

What happens if you would like to use a WinJS control in combination with Knockout? For example, a rating control. The patterns returned by ColourLovers contain a numHearts property. This is a floating point value between 0 and 5, which is perfect to show in a rating control. The HTML for the control looks as follows:

<div class="ratingControl" data-win-control="WinJS.UI.Rating"
     data-win-options="{ maxRating: 5 }"

On line 3 you can find the Knockout databinding. But, the average handler is not defined by Knockout. Because Knockout knows nothing about WinJS and its controls you’ll have to help it a little. I’ve added a TypeScript file to the solution, KoHandlers.ts and added following code to that:

ko.bindingHandlers["average"] =
    init: (element, valueAccessor, allBindings, viewModel, bindingContext) => {
    update: (element, valueAccessor) => {
        var value = valueAccessor() || {};

        if (element.winControl) {
            element.winControl.averageRating = value;

Make sure you add the .js file the .html file.

When Knockout initializes the binding the init function is called. To make sure the control is processed this is where we call WinJS.UI.process passing it the control.

When the value in the view model changes the update function is called. All we do is grabbing the value from the accessor, checking if the control is still there.

This handler does not update the view model when the user selects another rating. To implement something like that you’ll have to add an event handler to the init function and monitor the changes yourself.


I hope I’ve showed a bit how you could use Knockout in your TypeScript store apps. Now we’ve got the basics out of the way we can dive in a little deeper into using TypeScript in your Store apps next time. If you have any question or suggestions please leave them in the comments or send me tweet or email.

Demo application