Understanding JavaScript Modules

Understanding JavaScript Modules Headers

One of the first pieces of JavaScript you write with Angular is a module. Modules have been around in JavaScript for a while and are not unique to Angular. However, the term is often used to mean different things depending on the context. Some developers refer to specific JavaScript coding patterns as modules, such as the ‘module pattern’. Some developers denote modules by using a popular module specification such as AMD or CommonJS. Maybe you have even heard of the upcoming EcmaScript® 2015 module specification. How do these concepts fit with Angular and its module system?

This is the first in a series of posts to demystify the term ‘module’ in JavaScript and Angular. The key to understanding JavaScript modules is that you can’t point to any one thing as a ‘module’. What developers are really doing is writing modular JavaScript and there are many different techniques and tools to achieve this goal. This post discusses the benefits of writing modular JavaScript and some of the general techniques and tools you can use to achieve these results.

Components Versus Modules

You will see the term component used throughout this post. While the terms component and module are often used interchangeably, this post uses the term component to refer to a piece of software encapsulating a single-responsibility. It is the what that you are trying to achieve. Using modules or writing modular JavaScript, is the how. Writing a module is the approach in which you achieve this composition. Because there are different ways to write modular JavaScript, the meaning of the term module changes accordingly.

A Note about Angular Modules

This module information focuses on pure JavaScript modules. There is information dedicated to Angular modules, specifically the Angular 1.x variety but there are two reasons to explore the wider world of JavaScript modules. The first reason is that there is a vast set of tooling available today for working with modular JavaScript that work well with Angular 1.x and extend the capabilities of the Angular 1.x module system. The second reason is that Angular 2 is aligning with the EcmaScript 2015 module standard in place of the module system for Angular 1.x. What you will see is that by increasing your ability to write modular JavaScript, you will increase the quality of your Angular code and workflow today and these skills will translate to Angular 2.

Benefits of Modular JavaScript

What developer does not want to work with more readable and maintainable code? This topic becomes the heart of many development team discussions. Writing modular JavaScript allows you to write code that is easier to maintain and debug. Here are some of the benefits:

Single Responsibility

If you are familiar with the SOLID principles, single-responsibility is important in code construction. Single responsibility means that your application’s components are each responsible for one purpose or function. By dividing your code in this manner and naming the components appropriately, you can more easily identify where code should be placed or where to begin to debug your code. Writing modular JavaScript allows you to create and separate these components from each other so that each module has a single responsibility.

Encapsulated Internals

Encapsulation is another important concept in software design meaning that your components may have data or functionality that is not meant to be accessed by other components. By encapsulating this information, you create a barrier preventing external components from calling these internal concerns. A popular way to implement encapsulation in JavaScript today is the use of closures. The EcmaScript 2015 module specification also defines ways to encapsulate pieces of JavaScript.

Avoids Global Scope

While this is similar to encapsulation, global scope collisions often occur at a higher level in an application. When libraries attempt to use the same global variables or two pieces of a large application are written to use the same global variables, this condition often causes problems. These types of collisions are becoming less frequent especially in popular third party libraries. Using module specifications further diminishes the likelihood of a global variable conflict.

Use Separate Code Files

Once your code is separated into individual components, separating that code into multiple files generally increases maintainability. Now changes to components are clearly identified in source control as changes to the associated files. The challenge is to ensure that all of the individual files are loaded into the browser correctly or combined into a single file. There are tools to help in this area including loaders and bundlers.

Manage Dependencies

Once you have code separated, you need to manage which pieces of code are dependent on another. There have been several specifications developed to help manage these dependencies. While these specifications differ in their syntax, they provide two fundamental pieces: a way to define dependent modules (imports) and a way to define pieces of a module that can be used in other modules (exports). Frameworks have developed around these specifications to intelligently load the necessary modules both in the browser and in NodeJS.

Achieving Modular JavaScript

Now that you know why you should write modular JavaScript, there are general techniques available to accomplish this. Here is an overview:

Patterns

There are numerous existing JavaScript patterns available to you today. You see these basic patterns in constructing your Angular controllers and services. If you ever use the ‘controller as’ syntax in Angular, you are essentially using the constructor pattern. EcmaScript 2015 introduces classes to JavaScript and you can use them to write controllers in Angular 1.x and components in Angular 2. If you are looking to deepen your understanding of current JavaScript patterns, check out Addy Osmani‘s book, Learning JavaScript Design Patterns. The other techniques for organizing JavaScript help but writing quality JavaScript code is the foundation on which you will build your application so don’t skip this step.

Module Specifications

Module specifications help manage dependencies in JavaScript. If you want to separate your code into components, how can you use (and re-use) these components throughout your application? You use a syntax to define the components available to your application (also known as exports) and a syntax to define which components are required as dependencies in another component (also known as imports). Having a specification helps ensure open source libraries work well together.

The main specifications in use today are Asynchronous Module Definition (AMD), CommonJS, and the upcoming EcmaScript 2015 module specification. The AMD specification is more often used in the browser whereas CommonJS is the spec of choice in NodeJS and NPM. The EcmaScript 2015 standard seeks to eventually become the standard supported by the major browser vendors and it has some nice options for defining imports and exports.

Bundlers

A straightforward way to load JavaScript files in the browser is to add a script element to the HTML page. However, there are several issues with this approach. First, there is performance overhead for sending individual requests to the browser for each file. Second, you have to manually add all of the separate script references on the page and make sure they are listed in the correct order.

By using a bundler, you can mitigate the performance problem by having a process run as part of a build (a Gulp task for instance) which combines all of the script files into one file. Thus, you can reference only one script in your page and the browser only has the overhead of making one HTTP request.

Furthermore, bundlers often minify your code as well making the variable names as small as possible and removing white space. Additionally, they create sourcemaps that you use to debug the code in the browser.

Finally, when you use a bundler in conjunction with a module specification, you no longer have to maintain a long list of scripts. The order of loading the scripts is inferred by the modules’ dependency tree. Browserify is a popular bundler that leverages the CommonJS module specification and JSPM works with EcmaScript 2015 modules.

Dynamic Loaders

Bundling every single JavaScript file together into one request may not make sense for very large applications. You may want to load a base set of libraries and then optionally load in other dependencies. You can accomplish this manually but you can also use a dynamic loader.

A dynamic loader is a JavaScript library that runs in the browser and helps your application download additional dependencies only when they are needed. They work in conjunction with module specifications so that you don’t have to manually call the loader’s API, the dependencies are inferred from the specified imports.

The choice to dynamically load scripts or bundle them is application-specific. Oftentimes, these tools are used in conjunction with each other to minimize page load times. Popular loaders are RequireJS using the AMD specification and SystemJS using EcmaScript 2015 modules.

Angular Modules

Specific to Angular 1.x is the Angular module system. This system provides you with much needed dependency injection in large JavaScript applications. However, it lacks the features you get combining loaders and bundlers with other module specifications. You can use Angular 1.x modules in conjunction with other module specifications to get the benefits of working with bundlers and loaders.

Angular 2 is moving towards using standards based module systems like EcmaScript 2015 making it much easier to use the latest module tooling.

JavaScript Compilers

With all the mentions in this post about EcmaScript 2015 modules, when will the browsers support them? Quite frankly, it doesn’t matter if you use a compiler (sometimes called a ‘transpiler’). JavaScript compilers understand future versions of JavaScript, and emit JavaScript that is compatible with today’s browsers. If you want to use EcmaScript 2015 today (JavaScript essentially is EcmaScript by the way), consider using a compiler. Popular JavaScript compilers are Babel, Traceur, and TypeScript.

In Summary

While the term JavaScript module might be difficult to define, the concepts are here to stay. Remember why writing modular JavaScript is important. You want components with single-responsibility and encapsulation. These components should stay out of the global scope. You also want the maintainability benefits of keeping your code in separate files and you want to leverage dependency injection to use components together in a loosely coupled fashion.

Once you understand why to write modular JavaScript, there are many tools you can leverage to write your modules. Take time to learn about today’s JavaScript patterns. Understand your options with module specifications and use bundlers, dynamic loaders, and compilers to put it all together in your application.

This post introduces a lot of topics and future posts will look at these concepts in more detail. If there is a concept in which you are particularly interested, please leave it in the comments.

Code Camp NYC 2015 Talks

Code Camp NYC 2015

I had the pleasure of giving two talks at Code Camp NYC 2015. It was a great experience and I met many smart and dedicated developers. Here are the talks’ descriptions, slides, and source repositories. I will explore these topics more on the blog in the weeks to come.

Intro to JavaScript Modules

If you are a web developer, you have encountered JavaScript modules and hopefully you are using them. But if you aren’t or you think you can be using them better, this talk will give you the lay of the land for using JavaScript modules effectively. You’ll learn about the most common players like CommonJS, AMD, SytemJS and how they relate to the EcmaScript 6 standard. In addition, you’ll understand how to use tooling for combining and loading modules. There are many options and the choices can be overwhelming. By the end of this talk, you’ll know which technologies and frameworks can help to incorporate better JavaScript modules in your code.

Examples on GitHub

Angular 2 Tooling Today with Visual Studio

Angular 2 is the next evolution in Angular and along with the framework comes a recommended set of tools to increase developer productivity. Whether or not you are ready for Angular 2, you can start using these tools now with your current Angular projects. Attendees should have a basic understanding of Angular 1.x concepts. This talk demonstrates the fundamentals for using tools and frameworks such as TypeScript, SystemJS, and EcmaScript 6 in an Angular 1.x application. Armed with this knowledge, you can prepare for migrating to Angular 2 and more importantly improve your developer workflow today!

Example on GitHub

Angular Filters

Angular Filters

Angular filters are a convenient and simple way to format data in your application. Oftentimes, the values you use in code are not formatted for your users’ eyes. Whether they are currency values or dates, you need to process this data into a human-readable format.

Angular filters excel at formatting data. They are also used to process arrays to display collections of UI elements sorted, filtered, or paged. They are very powerful and with much power comes great responsibility.

This post covers what filters are, how they work, and general guidance to use them. For specific usage instruction for the built-in filters, the Angular docs do a very good job. Now it’s time to look at the basics.

Filter Basics

For those that didn’t read the last post on expressions, filters process the result of an expression before it is rendered. A simple example is formatting a number as currency.

Filter scenarios are generally simple input and output, but filters also accept parameters. In the case of formatting a currency, the built-in currency filter accepts a string parameter to change the currency symbol as well as a parameter to denote how many decimal places to display.

The syntax for filters is straightforward. After the expression you wish to filter, use the pipe character | to declare the filter. To set parameters, follow the filter name with a colon : and add the parameter value. Each subsequent parameter value is separated by a colon :. Using the built-in currency filter looks like this:

{{ vm.number | currency : '€' : 0 }}

The default currency filter displays the input with a currency symbol, commas to separate the thousand and million places, and also rounds the value to two decimal places. This example uses two parameters to change the currency symbol and to remove the decimals entirely.

In addition to the formatting advantages, the currency filter also rounds the decimal places. For instance using the above example, the value 999.9 displays €1,000 whereas 999.4 displays €999 – nice!

When using parameters, the order is important. For instance, if you want to leave the default currency symbol but also want to limit the decimal places to 0, you still have to pass the symbol as a parameter.

Another nice feature is chaining. You can chain multiple filters to format a single value. For instance if you want a date format with all uppercase letters, you can use two filters together.

{{ vm.date | date : 'MMMM d, yyyy' | uppercase }}

It’s important to note that the order matters. Processing flows from the leftmost filter to the right and subsequent filters can overwrite the processing done by a previous filter.

Preprocess Filters for Performance

When using a filter within a binding expression, it is loaded in the DOM. While the syntax is convenient, the performance implications can add up. To get a better understanding of how filters and expressions affect UI performance, read Todd Motto’s post on Angular performance. The important thing to remember is that anytime you add a piece of Angular code to your markup, you are adding processing to the $digest cycle. This $digest cycle runs repeatedly whenever a binding is changed in the UI and the amount of processing can easily increase by an order of magnitude depending on how you choose to write your expressions, bindings, directives, and filters.

For this reason, consider using filters within a controller or service of your application where it runs outside of the scope of the DOM and on-demand when needed instead of linked to the $digest cycle. Use the built-in $filter service to call a filter from a controller or service.

vm.preprocessCurrency = $filter('currency')(vm.number, '€', 0);

In this example, vm is the scope object in the controller. The $filter service is injected as a parameter to the controller function. If you understand how to use a filter in markup, using the $filter service in the controller is similar. First, pass the filter name as a string to the $filter service. Invoking this service returns the filter function which is why it is followed by a second invocation to process the data. The filter function’s first parameter is the data to filter, vm.number, followed by any other parameters. In this case, the currency symbol and the amount of decimal places are passed to the filter function.

This plunker demonstrates the two different filter approaches in action.

Anatomy of Custom Filters

Under the covers, filters are relatively simple JavaScript objects. Similar to other Angular objects, they are created with the angular.Module object.

angular
    .module('app', [])
    .filter('kittens', function () {

        return function (data, exclamations) {

            var kittens = 'Ooh, Kittens';
            exclamations = typeof exclamations !== 'number' ? 1 : exclamations;

            for (var i = 0; i < exclamations; i++) {
                kittens = kittens + '!';
            }

            return kittens;
        };
    });

The kittens filter converts any input into the value Ooh, Kittens! with an optional parameter to set the number of exclamation points (admittedly, probably only useful for this post). This is an example using the filter in markup.

{{ vm.someValue | kittens : 5 }}

To create the filter, use the module’s filter method which accepts a string representing the filter name as the first argument and a factory function as the second argument. The filter name must be a valid expression identifier and cannot contain any special characters, periods ., or hyphens -.

The factory function is a function that returns a new instance of the filter function. Because filters should be stateless, the factory function helps to ensure that output values are consistent, otherwise wreaking havoc on the $digest cycle. The factory function can also accept other dependencies as arguments.

This plunker demonstrates the custom filter.

Filtering it Down

Angular filters are a convenient and simple feature of the Angular framework. They help you format and process data in the view. They are flexible in that you can use them within controllers or services to preprocess data. And, you can write your own custom filters to re-use throughout your application.

Again, be sure to check out how to use the built-in filters in the Angular documentation. If there’s anything else you wanted to know about filters, please leave a comment. This post was created because an interested reader left a comment. Thanks Mariusz for the idea.

Angular Expressions

Angular Expressions Header

One of the first things a developer writes in Angular, other than the ng-app directive, is an expression. This is easily identified as the code written inside of a binding {{ }} or directive.

<input type="text" ng-model="name" />
{{'Hello ' + name + '!'}}

In this example, 'Hello ' + name + '!' is the expression. The official Angular documentation is pretty clear (maybe it wasn’t clear in earlier versions) that bindings and expressions are distinct items. However, there are (highly-ranked) places on the internet listed in search results that don’t always acknowledge the difference so readers beware. While you naturally find expressions and bindings together, they are not the same. This post is dedicated to explaining how expressions serve a broad and important role in the Angular framework beyond just data binding.

Expressions in a Nutshell

A better way to summarize Angular expressions is that they are a way to write JavaScript in HTML. Writing JavaScript in HTML? If you immediately cringe when reading that, it’s OK. You probably have been taught that you shouldn’t write JavaScript in your HTML because JavaScript is for functionality and HTML is for structure and you want to keep those concerns separate. Separation of concerns is still important when using expressions and thankfully Angular allows only a subset of JavaScript expressions in an HTML view.

The key differentiator of an Angular expression is that it is executed in an encapsulated scope. This means you don’t have to worry about global objects conflicting as you normally would writing JavaScript in HTML. In general, the scope in which an Angular expression runs is defined by a controller. If no controller is present, expressions execute against a default scope.

Also, expressions are converted to JavaScript functions using Angular’s $parse service. The $parse service provides many benefits and enforces certain limitations that you should understand.

Limitations or Separations of Concern

Angular expressions have limitations when compared to standard JavaScript. The limitations, however, are reasonable when you consider the role expressions play in the overall Angular framework.

There is no access to global variables or objects in Angular expressions meaning there is no access to the document or the window objects directly. To access these objects, use the testable $document and $window wrappers in your controller. Scott Allen has a good example illustrating this functionality.

Also, no control flow is allowed in an expression, meaning that you cannot use conditional logic (including ternary expressions), loops, or exceptions. You also cannot declare functions within an expression and you cannot use the comma or void operators.

There are also some limitations around which operators are supported. Even when they are supported, they may not work as you would expect. For instance while {{ 1 + 1 }} displays 2, if one of those values comes from a text input, the values will concatenate a string 11. Futher, the ++ operator is not allowed. Comparison operators such as >, <=, and == generally work as expected but you can save yourself some headache by moving this logic into a function on the controller.

Here are two expression examples. The first example demonstrates what is possible with expressions. The second example shows how to move the logic into a controller.

Powerful Expression Example

<!DOCTYPE html>
<html ng-app>
<head>
    <title>Dining Calculator</title>
</head>
<body>
    <input type="number" ng-model="totalBill" placeholder="Total Bill" />
    <input type="number" ng-model="tipPercent" placeholder="Tip Percentage" />
    <input type="number" ng-model="peopleAmt" placeholder="Amount of People" />
    <div>{{((totalBill + totalBill * tipPercent/100) / peopleAmt) || 'Calculating...'}}</div>
    <script src="Scripts/angular.min.js"></script>
</body>
</html>

Using a Controller

<!DOCTYPE html>
<html ng-app="app">
<head>
    <title></title>
</head>
<body ng-controller="Main as vm">
    <input type="number" ng-model="vm.totalBill" ng-change="vm.calculateTotal()" placeholder="Total Bill" />
    <input type="number" ng-model="vm.tipPercent" ng-change="vm.calculateTotal()" placeholder="Tip Percentage" />
    <input type="number" ng-model="vm.peopleAmt" ng-change="vm.calculateTotal()" placeholder="Amount of People" />
    <div>{{vm.totalPerPerson}}</div>
    <script src="Scripts/angular.min.js"></script>
    <script>
        (function () {
            'use strict';

            angular.module('app', [])
                .controller('Main', main);                

            function main() {
                var vm = this,
                    CALCULATING_MSG = 'Calculating...';

                vm.calculateTotal = function () {
                    var totalPlusTip = vm.totalBill + vm.totalBill * vm.tipPercent / 100;
                    var amtPerPerson = totalPlusTip / vm.peopleAmt;

                    vm.totalPerPerson = amtPerPerson || CALCULATING_MSG;
                }

                vm.calculateTotal();

                return vm;
            }
        })();
    </script>
</body>
</html>

You’ll see in the first example that the expression used is quite powerful. There is a fair amount of math involved and it can even check for the falsy value NaN in order to show valuable information to the user.

The controller example at first glance is significantly more code than the first. Looks can be deceiving, however. Once required to apply any validation or formatting to the first example, the expression won’t hold up because it requires the introduction of control flow into the logic – which is not allowed in Angular expressions.

Another key difference is found when looking at only the HTML markup. Even though there is more HTML markup in the controller example, it reads easier because the function names label what the expression does. In addition, debugging the logic in the controller example is easier.

Again, the generally appropriate way to handle Angular expression limitations is to keep logic out of HTML views and instead move it into controllers or services. The limitations help to nudge you into writing cleaner, more maintainable code.

Benefits

In the previous section, you saw how expressions offer a subset of JavaScript in HTML. Angular expressions also offer many benefits above and beyond what JavaScript typically provides including graceful handling of null and undefined, use with directives, and filters.

One area where Angular expressions shine is in their ability to gracefully handle null and undefined values. Here is an example of code that would cause problems with traditional JavaScript UI code.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <span id="dSpan"></span>
    <script>
        (function () {
            'use strict';

            var vm = {};
            dSpan.innerHTML = vm.foo;

        })();        
    </script>
</body>
</html>

When this code executes, the UI displays the word undefined. While having an undefined property in code is less than ideal, the user doesn’t need to see this. Further, if you expand the statement to dSpan.innerHTML = vm.foo.bar;, your application will throw a TypeError bringing your JavaScript execution to a grinding halt.

Here is an example of using an Angular expression for the same purpose.

<html ng-app="app">
<head>
    <title></title>
</head>
<body ng-controller="Main as vm">
    <span>{{vm.foo}}</span>
    <script src="Scripts/angular.min.js"></script>
    <script>
        (function () {
            'use strict';

            angular.module('app', [])
                .controller('Main', main);                

            function main() {
                var vm = this;
            }
        })();
    </script>
</body>
</html>

Run this in the browser and you see that the UI shows nothing for the undefined property. Change the expression to vm.foo.bar and even the TypeError exception is ignored. Convenient, indeed.

Angular expressions are one of the primary inputs for bindings and directives. This is part of the magic of Angular in the UI. The syntax is clean and generally easy to follow between the view and the controller. In addition to the binding examples already shown, many if not most built-in Angular directives take an expression as input.

<div ng-bind="expression"></div>
<div ng-class="expression"></div>
<div ng-click="expression"></div>
<div ng-focus="expression"></div>
<div ng-if="expression"></div>
<div ng-mousedown="expression"></div>
<!-- and many more...-->

Finally, expressions have a nifty feature called filters. Filters are a way to format the result of an expression for use in the UI. For example if an expression returns a number, the filter is responsible for formatting this number as currency before displaying it in the UI.

Filters are denoted using a pipe character | to the right of an expression followed by the filter name and parameters separated by colons. You can create your own custom filters. Here is a built-in filter example for currency formatting which displays the value $5,147.47.

{{ 12 + 5135.467 | currency:$:2}}

In Closing

This is just a peek into the world of Angular expressions – a feature used by all and misunderstood by many. They give Angular the syntactic ease upon which the framework loosely couples views to controllers.

Angular expressions are deceptively simple, purposefully limit their abuse, and offer delightful benefits to you, the developer. So the next time you open up those double curly braces or the first quote of an ng-bind attribute, write that expression with purpose and care.

Client-Side Productivity with Browser Link

Browser Link Banner

As you know Angular is a client-side framework – it’s home is in the browser. Visual Studio, on the other hand, has traditionally shined as the server development environment. Well there is a technology that attempts to bridge the gap between Visual Studio and the browser – it’s called Browser Link.

This post details Browser Link’s best features and discusses why you should use it. You will learn how to set it up when using static files for your Angular project and you will be prepared for some limitations and trade offs you may encounter. Overall you will find that Browser Link is a compelling and under-utilized tool in Visual Studio that you should add to your tool belt.

What is Browser Link?

Browser Link is a feature introduced with Visual Studio 2013 that runs when you press F5 to build, deploy, and run your project. It leverages the two-way communication of SignalR to send information from Visual Studio to the client and back.

While Visual Studio-to-client communication may seem trivial, this is a rich canvas on which to build truly time-saving features. For instance, think about how much time you spend in the browser’s F12 developer tools. What if you can link the work that you do in these tools to the code in Visual Studio? How many times do you duplicate CSS changes that you make in the browser by copying them to the correct file in Visual Studio? Browser Link makes this type of workflow obsolete by communicating changes between both the client-side and server-side development environments.

Setting Up Browser Link

There isn’t much to know to setup Browser Link. The two main requirements are that Browser Link is enabled and the project is running in debug mode. To enable Browser Link, press the Browser Link button’s drop-down arrow and press Enable Browser Link.

Enable Browser Link

Unless configured otherwise, debug mode is enabled by default when you run your project with F5. However to ensure you are running in debug mode, select Start Debugging in Visual Studio’s Debug menu.

Because many Angular applications use static HTML files instead of .cshtml or .aspx files, there is one additional configuration that needs to be added to the web.config file to enable Browser Link with static HTML files:

<system.webServer>
    <handlers>
        <add name="Browser Link for HTML" path="*.html" verb="*"
            type="System.Web.StaticFileHandler, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
            resourceType="File" preCondition="integratedMode" />
    </handlers>
</system.webServer>

For more on enabling Browser Link, read the corresponding ASP.NET documentation.

Finally, you should download and install the Web Essentials Visual Studio extension. The download and installation instructions are on the Web Essentials website.

Browser Refresh

The basic Browser Link scenario is Browser Refresh. This feature comes out-of-the-box and allows you to trigger the browser to refresh from Visual Studio. For example, you make a change to your client-side code in Visual Studio. Then for anything that doesn’t require a recompile, you would typically go to your browser and refresh the page in order to verify your changes. With Browser Link running however, you simply press the Browser Link refresh button or use the CTRL + ALT + ENTER key combination to save your files and simultaneously trigger the browser to refresh right from within Visual Studio.

Because Browser Link uses web standards, this works with any browser including mobile browsers on devices and in emulators. You can also trigger multiple browsers. If you want to check that your CSS animation runs across all of your application’s supported browsers, one button press or key combination refreshes all of them at the same time.

Web Essentials and Browser Link

Some of the most interesting Browser Link uses are found in the popular Visual Studio add-in Web Essentials. Web Essentials is a sweeping collection of tools. You should take a look for yourself when you have the chance – it’s good stuff. There are several features to discuss related to Browser Link.

Once you have installed the Web Essentials add-in and enabled Browser Link, there is a new Web Essentials toolbar that appears at the bottom of the page in your browser when you run your Visual Studio project.

Browser Link toolbar

This toolbar is displayed or hidden using the CTRL key. The toolbar provides several interesting pieces of functionality including two of the most useful: Save F12 changes and Inspect.

Have you ever spent time adjusting the CSS properties of an element in the browser to get just the right position, font size, or layout? The typical workflow is often then to copy the changes you made, if you remember them, into Visual Studio, save the files, and then refresh the browser to double check that you copied the CSS correctly. By using the Save F12 changes button, Web Essentials uses Browser Link to send the DOM changes back to Visual Studio and add them to the correct CSS selector in the correct file – it’s almost like magic.

Another feature is an easier way to find the source code for browser elements. In the past you may have found an element in the browser’s developer tools and then searched your project for the element’s id or class. Now, you can press the Inspect button on the Web Essentials toolbar to enable inspection mode. Once this mode is enabled, click on the element you are interested in and Visual Studio jumps to that markup in the appropriate code file – again, almost like magic.

Pro tip: hover over the buttons in the Web Essentials toolbar to see its keyboard shortcut.

Limitations and Trade-Offs

While the Browser Link technology enables some very useful scenarios, you should be aware of some issues that you may see. First, you are limited in Visual Studio by debug mode. Things like renaming or moving files can’t be done while running in this mode. Also, Browser Link sends a lot of network traffic so if you are using the browser’s network profiler, you may want to shut Browser Link off temporarily.

Furthermore, Web Essentials is often a proving ground for functionality before moving it into Visual Studio. You may encounter some functionality that doesn’t quite work as you expected. The key here is to try out the tooling on a non-critical project first to develop a comfort level and/or be sure to use source control or make a backup of your project. I use the features detailed in this post and find them to be stable and helpful. If for some reason the tooling doesn’t produce the output you were expecting, using CTRL+Z in Visual Studio to undo the recent changes typically works – but not always.

In Summary

Browser Link is a great Visual Studio feature for web developers. It helps to bridge the divide between development environment and browser tools to increase your productivity. It’s easy to setup and provides compelling features such as Browser Refresh, Save F12 changes, and Inspect. Regardless of whether you are using Angular or other web frameworks, you should give it a try.

The next post will dive into one of the first Angular features that developers use – expressions. They are included in practically every ‘Hello World’ Angular demo and it is important to understand what they are and what their role is in an Angular application – see you then!

Your First Angular Project in Visual Studio

angular-visual-studio

Today is the day. You have been hearing about Angular for a long time now. You have listened to the podcasts, you’ve watched the videos, and you have followed the pre-canned tutorials. Now you are creating your own project. Maybe you have an application idea or you plan to work your way through the documentation. You open up Visual Studio and pause. Which type of project template should you use? What type of back-end should you setup? So many questions.

This post looks to simplify the process and walks through a basic project structure in Visual Studio designed for quick setup and a solid foundation for separation of concerns. The structure aims for simplicity yet some of the recommendations may not be intuitive for the average ASP.NET developer. Angular is a client-side framework and therefore much of the ceremony performed to use ASP.NET for server-side development is unnecessary.

This walk through is for Visual Studio 2013. If you don’t have it, download the community edition (it’s FREE) and get the latest updates. Also install the Web Essentials extension to get the latest web development tooling for Visual Studio. If you have seen Visual Studio 2015, it introduces a new project structure that aids with client-side development. Even though this project structure is aimed at Visual Studio 2013, it should make it is easy to migrate to Visual Studio 2015 when the time comes.

Also, this post doesn’t cover build tools for bundling, minification, and testing even though Visual Studio supports these scenarios. Look for posts on these topics in the future.

Choosing the Project Template

This walkthrough uses a web application project as opposed to a web site project. This is part personal preference and part pragmatism. If you are significantly more comfortable with web site projects, go head and use them. It doesn’t make a significant difference for the purpose of this post.

Using a web application project is not straightforward, however. The tricky part is how the default templates setup things you don’t need – mainly everything specific to ASP.NET.

In the world of client-side frameworks, there is a much cleaner separation of client and server. There is generally no need to create .aspx or .cshtml files in order to render views on the server. Much of the rendering logic in these files can be done in Angular with static HTML files. There may be reasons to use server-rendered views for specific scenarios but start out considering that you don’t need server-rendered views.

“But what about data?” you say. Start out by using static .json files on the file system or hard code collections in your JavaScript. If you need to persist data, there are various in-browser technologies to save what you have done. Eventually yes, you will need to create a back-end but not for starting a basic Angular project.

Now it’s time to create the project. Go ahead and create an ASP.NET Web Application project.

create-first-vs-project

Press OK and this brings you to the dialog where you choose a template and select the features for your application. Choose the Empty template and uncheck all of the ASP.NET features.

create-empty-vs-project

Press OK to create the project. You see the project is indeed empty.

empty-structure

If you press F5 to run the project, you will get a 403 Forbidden error from IIS because there is nothing for you to access.

There is no need for server-side controllers, views or routes at this time. To start, add an index.html file to the root of your project, type Hello World in the body, hit F5 and you will see your friendly message in the browser.

Adding Angular

In order to write an Angular app, you need to reference the Angular JavaScript library. You can go to the Angular website and download it or reference it from the CDN (content delivery network). However, Visual Studio has the NuGet package manager to easily download the scripts and add it to your solution.

Note: in Visual Studio 2015, client-side dependencies will typically be loaded via client-side package managers as opposed to NuGet.

To load the Angular scripts from NuGet, right click on the solution and select ‘Manage NuGet Packages for Solution…’ from the dropdown. This displays the NuGet dialog. Search for “angularjs” and find the listing for AngularJS Core. There are other packages but this one provides the base Angular framework from the AngularJS Team (so it says). Click Install, select your web project, click OK, then Close to exit the dialogs and NuGet adds the Angular script files to your solution.

nuget-script-folder

Now create a script tag to reference the Angular script in your index.html file.

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

Creating a Basic Angular App Structure

Much of what is recommended here comes from John Papa’s information in this blog post and in his style guide. If you are going beyond this basic structure, reading the source material will give you tips to scale your application architecture.

First, start by adding an app folder to the root of your web project. Within the app folder, add two files: app.module.js and main.js.

The app.module.js file houses a single application-level module for your application. In this example, your application has an application-level module that loads the other modules of the application. The purpose of adding app.module.js as a separate file is to introduce the concept that modules, controllers, services, directives, views, etc. should be defined in their own files. Of course this is negotiable but it’s a good place to start. The contents of the app.module.js file should have the following contents.

(function() {
    'use strict';

    angular.module('app', []);

})();

This example uses an IIFE (immediately-invoked function expression) to immediately execute this code and also to encapsulate its scope. This pattern is used with every module. Also, notice the use of 'use strict'. This triggers modern browsers to run the JavaScript in strict mode. It is optional but it can help you avoid coding problems and many linters such as JSLint complain when it’s not included. The call to angular.module registers the module with the Angular framework.

In the main.js file, create a controller. In John Papa’s blog post, controllers do not use the word ‘controller’ in the file name. At first, I thought this was to save keystrokes, but he makes a good point about how this works with routing. However, there are numerous instances in Angular tutorials where ‘controller’ or ‘ctrl’ are used in the naming (including in John Papa’s style guide) so make the best decision for your projects – just be consistent. Here is the code for the main controller.

(function () {
    'use strict';

    angular
        .module('app')
        .controller('Main', main);

    function main() {
        var vm = this;
        vm.food = 'pizza';
    }

})();

In this IIFE, the controller is registered with the app module. An argument could be made to create a main module with which to associate the controller but being that this is the only controller in the project, this can be left out. Once the project grows in complexity, you should consider registering the controllers with feature-level or section-level modules and leave the application-level app module for registering these various sub-modules (read more in the style guide).

The function main is the controller itself. This controller is configured to use the controllerAs syntax. Again, John Papa details the benefits in his style guide. From the perspective of writing the controller, the big notable is that the properties and methods that you apply to scope are defined on this instead of an injected $scope parameter. Most examples I have seen online for Angular use $scope so this may be new to you. In addition, notice the use of the variable vm to capture the scope. This practice helps to avoid any confusion if/when you define nested functions also using the this keyword.

Finally, take a look at the index.html view. Here is the code.

<!DOCTYPE html>

<html ng-app="app">
<head>
    <title></title>
</head>
<body ng-controller="Main as vm">

    <input type="text" ng-model="vm.food" placeholder="Enter food" />

    <p>Sriracha sauce is great with {{vm.food}}!</p>

    <script src="Scripts/angular.min.js"></script>
    <script src="app/app.module.js"></script>
    <script src="app/main.js"></script>

</body>
</html>

First you see the ng-app directive set to the app module to bootstrap the application. On the body tag you see the use of the controller as syntax in the view. Something to note, the use of the name vm in the view has no correlation to its use in the controller. The two variables can have different names. Next, you see the basic example of using the vm scope with a simple input scenario where the value of the input is bound to the expression vm.food. Finally, all of the scripts are referenced on the page.

After completing these steps, your application structure looks like the following.

final-structure

When you run the application you should be able to pair your favorite food with the infamous Rooster Sauce.

final-interface

Conclusion

To those of you who have been using the full breadth of ASP.NET over the years, using static HTML files may seem like a foreign concept and admittedly the ASP.NET project templates tend to favor server-side views.

However, now you have a project that feels like other ASP.NET projects you have worked on. You are still pressing F5 to startup IIS Express and the HTML and JavaScript editors are the ones that you are used to using.

You also have a starter Angular application with basic separation of concerns. You even have a naming convention to use for your modules and controllers as well.

If you would like to download the finished project, you can do so on GitHub.

In the next post, you will learn about a Visual Studio tool called Browser Link. It provides useful features especially for client-side development but there are some tricks to setting it up with static files. Until then, enjoy experimenting with your new Angular project.

Learning Angular Quickly

When approaching the task of learning Angular, it can be overwhelming to figure out the best content with which to get started. Here are the pieces of content and the activities I think will help you get started quickly.

Listening to Podcasts

You probably have time during the day when you can’t code but can listen to a podcast. Many people listen to podcasts or audiobooks on their commute, doing yard work, or when their boss is talking to them (just kidding Andy!). I’ve been using podcasts to learn programming from the beginning. Even if the material is beyond my current understanding, I find the immersion very useful for determining what to focus on when I do sit down and code.

For podcasts, Adventures in Angular from DevChat.TV is my favorite. The podcast is released weekly and covers an array of topics including how to get started, interviews with the Angular team, and practically all other areas of using the framework. The host, Charles Max Wood, has assembled a panel consisting of the “who’s who” in the world of Angular including John Papa, Joe Eames, Lukas Ruebbelke, Aaron Frost, and Ward Bell. The show typically runs for less than an hour and I often feel as if I’m hanging out with a group of (really) senior developers at a bar or coffee shop – laughing a lot and learning a ton. The show is less than a year old at this point so I recommend starting from the beginning and getting caught up on the recent history of Angular in addition to learning from some of the best.

Using Quick Start Tutorials

By “quick start tutorial”, I mean a tutorial that succinctly covers all of the high level aspects of the framework. I have looked at a handful of these and my favorite is by Lukas Ruebbelke on egghead.io. There is a handy GitHub repo that accompanies the course so download the initial project and then write code while watching the videos. I’m a fairly experienced jQuery developer and I found this video had the right pace as I could easily duplicate the HTML and JavaScript and really focus on the Angular details and structure.

Also, Todd Motto’s Ultimate guide to learning AngularJS in one day blog post is appropriately comprehensive for someone getting started. While it’s not a tutorial, he covers the main concepts and terms in Angular accompanied with code examples. Especially in conjunction with listening to podcasts, this post can help you translate the concepts you learned from audio into code on the screen.

There are certainly other tutorials. In fact, angularjs.org has three of them incorporated into the site. There’s one on the home page itself with videos, one tutorial in the documentation, and then also prominently displayed is a link to a code school tutorial. If you want, look at them all. But remember the goal here is to learn Angular, not review quick starts – don’t ask me how I know.

Writing Code

This is really what we are here to do. The podcasts and the quick starts are great, but at some point you will be left to your own devices to write code. This is something that I’ll be writing a lot more about but it’s important to remember that as good as it is to have podcasts, video training, etc., you won’t gain expertise until you write lots of code and push yourself to solve new problems.

Once you start writing code, this is where I expect you will use the Angular Developer Guide, API Docs, and internet search as a reference to solve specific problems and deepen your understanding of the framework’s functionality.

Blogging

Blogging can be helpful in many ways. By writing, you will often find that you don’t understand things as well as you thought you did. Once you have to start choosing the right words to put down on the page, you’ll start fact checking yourself. There is an important learning opportunity when readers comment on your posts including information from their own perspective. Also when there are readers, the accountability level goes up. There’s more of an incentive to continue the conversation and learning. (PS – thanks to everyone reading here!)

You should understand that blogging takes time away from coding but I’m convinced that the time spent is worth it. If you want to take this step, I found this free mini-course by John Sonmez instrumental in getting setup quickly.

Attending Community Events

Luckily where I am located, there are many user groups where developers can link up with other developers. Take a look on meetup.com to see if there are any near you. I recently attended the Philly.NET Code Camp and learned about technologies including Angular, Ember, React, TypeScript, and ECMAScript 6.

The talks were informative but just as important is that this event had a built-in after party. This is where I hung out with some of the presenters and discussed the finer details of these technologies. For instance, how beneficial (or not) are classes in EcmaScript 6? Spoiler alert, there is no definitive answer but by being a part of this discussion, I now understand some of the finer points to consider when choosing to use this feature or not. This learning is incredibly valuable and not often found when watching pre-recorded presentations.

In addition, you may decide to speak at an event like this one day. Take notes not only on the technology you are learning but also notes about what pieces of the presentations work well or what falls flat. This will give you a head start developing your speaking style.

Video Training

Another useful set of content is video training. I use Pluralsight which currently has 1,271 video courses covering a vast array of technologies. At the time of writing, a search for ‘AngularJS’ on Pluralsight returns 42 courses. Some people really do well with video training. Because it’s not a replacement for writing code, I tend to use it during times when I can watch a video but can’t necessarily type easily such as when I’m on the treadmill. I also may listen to more conceptual courses or re-listen to courses in the car where I don’t rely on looking at the screen to absorb the information.

Some of the courses on my radar for Pluralsight are: Building a Site with Bootstrap, AngularJS, ASP.NET, EF and Azure by Shawn Wildermuth, AngularJS for .NET Developers by Joe Eames and Jim Cooper, AngularJS Patterns: Clean Code by John Papa, AngularJS In-Depth by Lukas Ruebbelke, and HTML5 Offline Applications with Angular, IndexedDB and Bootstrap by Craig Shoemaker. There are so many more that look great – it’s an embarrassment of riches.

Other Techniques

This list is by no means exhaustive. For instance, you can contribute to open source. You can start your own podcast or user group. You can analyze the Angular source code, watch YouTube videos of ng-conf, pair program, read books, and many more. These are all great ideas and I’ll write about as many of these as I can.

In summary, the community has done a great job creating content for Angular. There are almost too many choices and there are only so many hours in a day. Hopefully, I’ve been able to shed light on a selection of content and provide tips for you to learn Angular quickly. Happy coding!

Which Angular Version Should You Learn?

angular 1 or 2?

If you are just starting with Angular, should you learn Angular 1.x or Angular 2.0? There are numerous resources available for all versions of Angular, but there’s only one version that you can pick for your first project. Which is the right one?

Also, you may have heard that Angular 2.0 is a significant departure from 1.x. Should you attempt to stay ahead of the curve and start with Angular 2.0? Which version will give you the best browser support? There is much to consider so this post is a summary of what I’ve found and what I recommend.

Angular 2.0 is Coming

Potentially the biggest question for Angular 2.0 pertains to the release date. Both Shawn Wildermuth and Craig McKeachie note that they expect Angular 2.0 to be released in late 2015. I haven’t seen an official date from the Angular team (maybe I’m missing it somewhere), however Brad Green provided some hints at the recent 2015 ng-conf keynote. Apparently, some teams at Google will start migrating their applications from Angular 1.x to Angular 2.0 starting in May 2015. He continues, “we are going to take the learnings from (this) and the feedback from all of you who use Angular 2.0 to determine when we are done and we can call it ready”. It is plausible that a fully-baked release of Angular 2.0 will be here in a matter of months. That being the case, you will at least want to pay attention to its progress.

However, take a look at the Angular 2.0 download page. The current build is listed as alpha. While alpha builds can be valuable for evaluating new features and improvements, they can be problematic for learning. You can reasonably expect to run into bugs or even find a drastically redesigned API by the time the first release candidate hits. As someone starting to learn a framework, you have an uphill battle already without the framework pushing against you.

Continued Angular 1.x Support

Also during the ng-conf 2015 keynote, the Angular team clarified they will not immediately seek to abandon Angular 1.x. While the team wants to super-heroically move the web forward, they are going to measure the traffic between the Angular 1.x website and the Angular 2.0 website to help determine 1.x support. Presumably if 1.x continues to show traction, they will continue supporting it. After the announcement of Angular 2.0, both K. Scott Allen and Dan Wahlin posted their thoughts. In summary, they can recommend continuing to use Angular 1.x going forward no matter the verdict with Angular 2.0. For some applications, it doesn’t make sense to invest time and money in a big migration. Therefore as an Angular developer, you should be prepared to maintain existing Angular 1.x applications for some time to come.

The Angular team is also considering the migration path. The Angular 2.0 router will be compatible with 1.x. The team also plans to offer several migration options and John Papa has volunteered to help create the migration guide. This points to an important skill for Angular developers to adopt in the not-so-distant future – migrating from 1.x to 2.0. In the short term, development teams will have valid options to stick with 1.x or move to 2.0 but the Angular team’s goal is to make it very attractive for teams to migrate. Therefore you should hone your skills accordingly and consider that you will likely need to know multiple framework versions.

Internet Explorer 8 Support

If you need to support IE 8, know that Angular 1.3 drops support for it. Being an ASP.NET developer who currently supports IE 8, I thought this was a deal breaker. But while there is no explicit support for IE 8 in Angular 1.3, it hasn’t been explicitly removed either and depending on what you do with Angular 1.3, it could still work.

Skimming through the migration guide from Angular 1.2 to 1.3, it appears certain, less-reliable, pieces of the API were deprecated. Potentially by starting with 1.3, you would write more reliable Angular code even if you eventually back port the project to 1.2 for specific IE 8 support at a later date. The guide also notes that 1.3 will require shims to work correctly in IE 8 which is only a minor hurdle. Another sign of hope for IE 8 support is this GitHub project which forked the Angular 1.3 source code with the intention of preserving IE 8 support – go community!

Drumroll, Please

By no means is this a one-size-fits-all decision but if you’re just starting to learn Angular, the latest version of 1.3 is most likely the best with which to start. It’s capabilities are well-understood. It’s also stable and the browser support appears sufficient. Of course when 1.4 is released, you should re-evaluate.  And finally, track the progress of Angular 2.0 and consider evaluating it after you get your feet wet with Angular 1.3.

In the next post, I’ll detail my favorite resources for learning Angular quickly and discuss strategies for mastering the material.

Angular First and Foremost

Angular ShieldWelcome! This is the first post in what I expect to be a fun and educational journey into the world of Angular – specifically for those writing software on the Microsoft stack.

Angular is going through a period of substantial change. Angular 2 is on the horizon and along with the adoption of new features and performance improvements, the community is preparing for a non-trivial upgrade effort. The Angular team appears to be closely listening to feedback and we can expect them to continue addressing developer needs. To better understand the changes, I recommend watching the ng-conf 2015 Day 1 Keynote.

On the server, the .NET Framework is undergoing a sea change. The core framework is open source and ASP.NET is now ‘cloud-optimized’. Visual Studio even has a FREE Community Edition. Furthermore, the recent friendship between Angular and TypeScript makes this a good time to evaluate developer productivity using Angular with the latest Microsoft frameworks and tools.

I’ll be honest, I haven’t written a single line in Angular. I’ll be learning from scratch – maybe like you. I’ll be drawing on my 7 years of experience developing ASP.NET applications and I expect that as I document my learning, I can help to curate the best resources for you on your journey with Angular.

One of the blessings and curses of software development is the rapid pace of change. Web developers have more to learn than ever and we want to get things done quickly with frameworks and tools we can depend on. My goal is to make it easier for you to decide which pieces to use and how to use them. If there are any specific topics you want covered, let me know. For now though, I’m starting with Angular First.