Tuesday, April 22, 2014

Video: A JavaScript Feed Reader in Under 10 Minutes Using Angular JS

An important component of the decision to use a framework should be the amount of ceremony and ritual involved. You must carefully weigh what it takes to ramp up on the technology and how common tasks are performed. It does no good to adopt a library that forces you to solve a problem with more effort than it would take using your basic tools. One of my favorite examples to showcase technology is a simple feed reader. Several years ago I recorded a video to demonstrate how to build a Silverlight MVVM Feed Reader from Scratch in 30 Minutes. It opened a lot of eyes for people who thought MVVM was overcomplicated.

HTML5 and JavaScript have matured significantly and it turns out it is even easier to build a similar application from scratch using tools like Angular (I even throw in some Twitter Bootstrap styling so it looks halfway decent). One of the things I really like about Angular is that it is really doesn’t involve a lot of ritual or ceremony. In fact, in this video I probably take too much time doing things like setting up a title and writing constructor functions instead of just in-lining the code for my controllers and services.

Nevertheless, I manage to make a functioning feed reader entirely in the browser from scratch in less than 10 minutes. In the video below you’ll see how to bootstrap Angular using the Content Delivery Network (CDN), set up your initial app, add a controller, then add a service and wire everything together. I even show you how the built-in forms controller automatically handles disabling the submit button for me when I specify the input type as a URL and note that it is required. Enjoy this video as it illustrates how Angular can save you time building your web-based apps:

Angular JS Feed Reader in Under 10 Minutes.

If you are interested in learning more, check out my course on Mastering AngularJS and read about consulting and training opportunities. Grab the source and run the demo for the feed reader yourself right here.

Monday, April 21, 2014

Learn Angular JS, Explained with Answers, Videos and Fiddles

Having worked on various enterprise Angular projects our teams have been faced with myriad challenges to overcome and has quite a bit of “in the trenches” experience. I share what I can with other developers through my various blog posts, by answering questions on StackOverflow and through a large collection of JavaScript fiddles. I also realized early on that Angular is a very important library and began recording a video course to help others Master Angular JS. The course has grown to well over 8 hours of content (yes, a full DAY of Angular!) and there are still several lessons left to record. In this post I organize some of the content and resources I’ve created as a guide to help you link into information, code snippets, and other information that may help you build your Angular apps.

If you’re in the early stages of learning Angular, you might ask yourself “Why?” That’s why I wrote 10 Reasons Web Developers Should Learn AngularJS. I attended one of the first Angular conferences in the U.S. that sold out in minutes, and had the opportunity to meet with other .NET developers and record a video panel discussion about Angular and the .NET World.

With an early version of Angular (and TypeScript) I also wrote a fairly large project that you can browse. I describe it in my blog post, “Commodore 64 Meets Angular JS and TypeScript.” Have fun running the emulator or click on the specs links to see unit tests. Visit CodePlex for the full source.

Fundamentals of AngularJS

One of the things that really drew me to Angular was the simplicity and lack of ritual. There is not a lot of set up or hand-waving necessary to get an app up and running. Take a look at a mini-app from scratch that echoes what you type:

Angular app from scratch: http://jsfiddle.net/jeremylikness/BzmfT/

There is a lot more to it, and I cover it all in the Fundamentals of Angular lesson. The best place to start learning about it is at the beginning. In the inaugural video in this series, I lay the groundwork for later modules by introducing scope for data-binding, controllers for MVC on the client, events, filters to format output, directives to extend the HTML vocabulary, modules to group code, services to provide application-wide functionality, and routes to enable Single Page Applications (SPA).

Note: All of my links to WintellectNOW videos can be accessed using the code LIKNESS-13. This offers a free trial. Although it will require a credit card, you will receive 2 weeks of unlimited access with no obligation – you can cancel at any time.

Despite how simple it is, Angular is incredibly flexible and customizable. For example, here’s a little fiddle that shows how you can even bootstrap Angular manually as needed:

Bootstrapping Angular manually: http://jsfiddle.net/jeremylikness/wMF4x/

Scope and Digest Loop (Data-binding)

The key to using Angular is to understand how it’s data-binding works via the scope and the digest loop. The lesson I recorded (Angular Scope and Digest Loop) covers scope, expressions, hierarchy, UI patterns, prototypical inheritance, the DOM, how to access scope externally, the lifecycle (including apply, digest, and destroy), watches, and events. Together with the digest loop, scope facilitates data binding by providing the glue between declarative HTML and imperative program logic. You’ll learn about the scope lifecycle, how scope interacts with the HTML DOM, and the various functions the scope provides including expression evaluation, property-change notifications, and events.

Did you know you can train Angular to watch properties on external objects? I have an example here: http://jsfiddle.net/jeremylikness/Ts9p4/ 

It’s easy to do cascading selections: http://jsfiddle.net/jeremylikness/7dUyf/

Here’s how to create a task to fire an update in a subsequent digest: http://jsfiddle.net/jeremylikness/bWeQL/

It’s quite common to throttle parsing of input: http://jsfiddle.net/jeremylikness/5KeMw/

Another example of watching for changes in objects outside of Angular: http://jsfiddle.net/jeremylikness/HU7Wn/

Set a deep watch on a single property: http://jsfiddle.net/jeremylikness/GrRtK/

Copying lists: http://jsfiddle.net/jeremylikness/xdzxb/

Handle events: http://jsfiddle.net/jeremylikness/BPX49/ 

Up/Down vote example: http://jsfiddle.net/jeremylikness/bPQXJ/

Intercept a form post: http://jsfiddle.net/jeremylikness/T6B2X/ 

Filters

Filters provide a declarative way to format data in the presentation layer of Angular apps. XAML developers will recognize filters as an HTML version of value converters. I cover all of the filters that Angular ships with that format currency, dates, times, filter and sort lists, and much more. I also show how to write tests for filters and walk you through creating a custom filter of your own. The Advanced Filters lesson covers the built-in filters like currency, date, filter, json, limitTo, number, and orderBy, then shows how to create custom filters, filters that take parameters and even have dependencies on other services.

Here’s how to create a filter that throws an exception when a data-binding property is not defined: http://jsfiddle.net/jeremylikness/BHjRg/ 

Dependency Injection

Enterprise and line-of-business applications are often composed of multiple interdependent components. Angular provides a set of services that enable management of dependencies and component lifetime, configuration of services, and even service interception to extend existing functionality. In my Dependency Injection lesson you can follow along while I build a sample app (on the fly – it’s mostly live coding) and then refactor it to use inversion of control. From factories and services to providers and interceptors, you don’t want to miss out on the rich features Angular provides for dependency injection on the client.

Here’s a walkthrough of what is covered in the video purely in code:

1. Manually wiring it up: http://jsfiddle.net/jeremylikness/PK2fB/
2. Inversion of Control: http://jsfiddle.net/jeremylikness/PK2fB/1/
3. Angular DI: http://jsfiddle.net/jeremylikness/PK2fB/2/ 
4. Using providers: http://jsfiddle.net/jeremylikness/PK2fB/3/ 
5. Using decorators: http://jsfiddle.net/jeremylikness/PK2fB/4/ 

Here’s how to build a dynamic factory: http://jsfiddle.net/jeremylikness/QM52v/ 

Blog post: Understanding Providers, Services, and Factories in Angular

What if you import two modules that have a service with the same name? Solve it like this: http://jsfiddle.net/jeremylikness/xEt94/

See services vs. factories in code: http://jsfiddle.net/jeremylikness/7dUyf/

Or even providers vs. services vs. factories: http://jsfiddle.net/A6Cb2/7/ 

Services

In Angular, the term "services" refers to singleton references to objects and functions that carry out specific tasks. Angular provides several built-in services for everything from manipulating the URL in the browser, running code at regular intervals, and interfacing with Web services to managing asynchronous workflows using JavaScript promises. My Angular Services lesson walks through the core services shipped with Angular by providing detailed hands-on examples and covering advanced topics such as promises, strict contextual escaping, and how to interface with various providers to configure the behavior of built-in services.

Here’s examples of parsing expressions various ways: http://jsfiddle.net/jeremylikness/CAHKE/

Returning a promise using $q: http://jsfiddle.net/jeremylikness/HL7h2/

$q.when: http://jsfiddle.net/jeremylikness/Q2jMG/

$q.all: http://jsfiddle.net/jeremylikness/UzXzq/

Deferral: http://jsfiddle.net/jeremylikness/PhZYb/ 

Synchronizing the state of a form: http://jsfiddle.net/jeremylikness/Gz77C/

Web Services

For years, AJAX has enabled developers to write asynchronous, responsive Web applications. Issuing requests from your browser just got easier with the built-in services provided by Angular that support the full suite of HTTP verbs as well as JSONP. In my Angular Web Services lesson, learn how to interact with Web pages and Web services using Angular $http and $resource services, how to transform requests and responses with interceptors, and how to secure your app against JSON vulnerabilities using cross-site request forgery (XSRF) tokens. I conclude the lesson with a demonstration of how Angular’s Web services can be mocked out of the box to facilitate unit testing without having to spin up your web server.

To get a taste for what the course covers, check out the Web Services example project: https://github.com/JeremyLikness/AngularWebServices and browse the various web service examples live.

An example of using $http interceptors: http://jsfiddle.net/jeremylikness/rWRA3/2/

Directives

Directives are a powerful feature that enables reuse of controls, much like the proposed Web Components specification.There will be two directives courses added to the library shortly by my colleague Dave Baskin, who authored the Angular MVC Cookbook. The page also links to his series of blog posts on the topic. I look forward to adding those videos. Until then, you can check out:

Examples of scope isolation in directives: http://jsfiddle.net/jeremylikness/3pvte/

Blog post: Synergy Between Services and Directives in Angular JS

Using a service to communicate with a directive: http://jsfiddle.net/jeremylikness/wqXYx/1/ 

Data-binding to a sub-property: http://jsfiddle.net/jeremylikness/Q6jKD/ 

Routing

Single Page Applications (SPAs) enable rich desktop experiences for users without requiring pages to rerender or post back to the server. However, special care must be taken in SPAs to provide a consistent user experience by enabling the back and forward buttons and allowing pages to be bookmarked in various states. In the Routing lesson, I cover the Angular team's ngRoute module as well as the third-party Angular ui-router module and demonstrate their utility in SPAs. Learn how to configure routes, render templates, and resolve promises in an action-packed lesson that includes two complete, fully functional examples built using two different route providers.

Check out what I cover by browsing and running the Angular Routes example project (ngRoute and ui-router): https://github.com/JeremyLikness/AngularRoutes 

Testing

Angular was built from the beginning to support testing. The next lesson I’ll release is going to cover testing with Jasmine. Here’s some code and a blog post that cover a bit:

http://jsfiddle.net/jeremylikness/h8DS8/

Testable Filters with TypeScript, Angular JS, and Jasmine

Advanced

I categorize these posts as advanced just because they cover topics related to very specific scenarios you may run into. The blog posts all come with full source in their respective links.

Using Zone to Trigger Angular Digest Loop for External Functions
Instrumenting Angular with Zone
Interception Using Decorator and Lazy-Loading with Angular JS
Throttling Input in Angular JS Applications using Underscore Debounce

Migration

A lot of what we do is help enterprises migrate from existing platforms like Silverlight to modern solutions. We’ve done this enough that we wrote a white paper about it! I wrote about the similarities between XAML and Angular in this post about Migrating from Silverlight and you can download the whitepaper directly from this link.

Conclusion

I was very surprised when I took inventory and realized how much I’ve written about Angular and how many sample projects and code snippets I’ve been able to publish. If you’re like me, you would much rather have a single place to reference to jump to links when and where you need them. Although I am not quite ready to take on the task of indexing everything available on the Internet, I can certainly take the time to organize my own resources as in this post. I strongly urge you to check out my course as well. The LIKNESS-13 code will not only gain you access to that course, but also 250 other videos covering everything from Node and the cloud to C# development, algorithms, data structures, and almost anything else you might like to add to your programming arsenal.

What are you doing?

I’m amazed at how quickly Angular has been adopted. I can see the enthusiasm in the user groups as the attendance swells and hear the sense of urgency from customers as they look at legacy platforms and try to determine what the best approach to taking their enterprise to the web will be. I’m very interested to learn what projects you are working on and where your interest in Angular comes from. If you have a minute, take some time to drop a comment below and let us know about your Angular work or questions you might have!

Thanks, and happy coding.

Sunday, April 6, 2014

JavaScript Chaos with Canvas

I learned about chaos theory quite by accident. On a family vacation we stopped by a campground along the Blue Ridge Parkway in the Appalachian Mountains. I was not an outdoor enthusiast at the time so while my parents were hiking I preferred to head over to the arcade to play Donkey Kong and Tempest. One rainy day even the video games were boring so I sauntered over to the main cabin and started leafing through their modest library of books. In between westerns and romance novels I glimpsed a book with the intriguing title Chaos: Making a New Scienceand ended up reading it from cover to cover.

To put things in perspective, this was not the 2008 edition with a fancy new cover. This was the original 1987 edition and the copy I grabbed was only a year old. What I loved about the book was the fact it didn’t just cover various aspects of chaos theory but also shared the actual equations and algorithms used to generate the various fractals and graphics. At the time I had a graphing calculator and was able to program most of the examples.

The beauty of chaos is that most functions are iterative and the fact that “period 3 implies chaos” means some very simple equations can provide impressive results. Take, for example, the bifurcation diagram. The equation it is based on is simple:

f(x1) = R * x0 * (1 – x0)

That is, to get the next value for x, subtract the previous value from 1, multiply by itself and a factor called “R.” R is a sort of arbitrary constant that relates to environment. Presumably lower R means lower resources and higher R means higher resources. If you plot across values of R, what you find is that in many cases the population does what you might expect and stabilizes at a certain value. For higher R, things get interesting. The population can explode, causing over-crowding and therefore starvation resulting in a drop that then grows, etc. and fluctuates between two levels. As R approaches 4, things get even more interesting and it ends up with a seemingly random spread of values. However, within the increasing values you can find little bands or breaks in the pattern where the population stabilizes to a single value again. If you were to blow up those regions you’d find they look very similar to the overall graph, a feature referred to as self-similarity.

The addition of the canvas tag also makes it easy to play with these equations in the browser. Working with a canvas is straightforward. Define it in your HTML and reference it in your JavaScript. Grab a context – in this case I’m using a 2-dimensional context – and use the context to draw. Here’s some definitions for the iterator function.

var c = document.getElementById("c"),
        ctx = c.getContext("2d"),
        w = c.width,
        h = c.height,
        st = 2 / w,
        fx = function (x1, r) {
            return r * x1 * (1 - x1);
        },
        it = function (r) {
            var idx = 0,
                x = 0.5,
                xc = w * ((r - 2) / 2);
            while (idx++ < 2000) {
                x = fx(x, r);
                ctx.fillRect(xc, h - (x * h), 1, 1);
            }
        };

Note I’m figuring out how many pixels I can use to step over R values but otherwise I’m just running through the iterator function and plotting 1 x 1 rectangles. Next, I set the fill style then iterate over R and use the timeout function to queue up the rendering without blocking too much of the UI thread:

ctx.fillStyle = "rgba(32,64,128,0.05)";
    for (r = 2; r < 4; r += st) {
        (function (r1) {
            setTimeout(function () {
                it(r1);
            }, 0);
        })(r);
    }

This short amount of code produces an amazingly intricate graph, as you can see here:

Another example I love for its simplicity is called “the chaos game” and generates what is referred to as Sierpinski’s gasket. The game is simple. I pick three starting points that help bound/define my shape. Then I pick a random point we’ll call the “game point.” In each “turn” of the game, I roll a 3-sided die and determine which one of the starting points I’m going to use. I calculate a point halfway between the game point and the base point I picked, and that becomes the new game point. That’s it – each turn is picking one of three base points, traveling halfway to that point from an arbitrary spot, then plotting it. Here I define a the initial points (you can see they form a sort of triangle), generate my game point, provide some helper functions for getting a random number and plotting a point, and create my iterator function that will run 10,000 times.

var c = document.getElementById("c"),
        ctx = c.getContext("2d"),
        w = c.width,
        h = c.height,
        rfn = function(b) { return Math.random() * b; },
        px = [0, w/2, w],
        py = [0, h, h/2],
        gx = rfn(w),
        gy = rfn(h),
        pl = function(x, y) { ctx.fillRect(x, y, 1, 1); },
        iter = 0;
        i = function() {
            pl(gx, gy);
            pt = Math.floor(rfn(3));
            gx = (gx + px[pt])/2;
            gy = (gy + py[pt])/2;
            if (++iter < 10000) {
                setTimeout(i, 0);
            }
        };

To kick things off I set the fill style then call the iterator function. The result is amazing.

These are just a few of the simple yet elegant ways JavaScript can chart the mysterious terrains of chaos theory. I also consider this a metaphor for just how far the web has come. I still remember writing these routines in C++ on my old IBM PC and waiting for 20 minutes while the bifurcation diagram rendered on an 800 x 600 display. It is amazing how fast JavaScript is able to crunch these numbers and the browser is able to render the graphics in mere seconds. Computing power and the web have certainly come a long way. 25 years later, I still get excited about chaos theory and am reminded of why I fell in love with programming in the first place: it only takes minutes to take an abstract idea like a mathematical formula and use code to turn it into a tangible, discernable image on your display. That, in my book, is magic.

If you want to learn more magic, check out Jeff Prosise’s lesson on the HTML5 Canvas API. Use promo code LIKNESS-13 to watch it for free!