Thoughts on Angular's Controller As Syntax

Monday, August 11, 2014 by K. Scott Allen
10 comments

I’ve been a bit late to the Angular controller as syntax. I was skeptical of the feature at first, and with an Angular project already in flight, I felt it wasn’t the type of change to make with a significant amount of code already committed.

The controller as syntax allows me to alias a controller in markup.

<div ng-controller="MainController as main">
    {{ main.title }}
</div>

Then instead of injecting a $scope into the controller, model data and behavior is added to the controller instance itself.

app.controller("MainController", function(){
    this.title = “Hello!”;
});

Behind the scenes the controller as syntax adds the controller alias (main in the above example) to a scope object, because Angular still evaluates all binding expressions against a scope object.

Here’s what I think about controller as now.

The Good

- Using the controller alias in a view is a push into the pit of success. View code is more explicit and easier to maintain. Even when using $scope in a controller, I’ve come to view any reliance on prototypal inheritance in the scope chain with suspicion, as the inheritance is brittle, subtle, and often complicates both controller and test code. With a controller alias there is no reliance on scope inheritance hierarchies.

- Not having to inject a $scope makes test code slightly easier.

- Having no access to the $scope API inside a controller is a good thing. I’ve come to view any use of $scope.$watch, $scope.$emit, $scope.$on, and $scope.$* in general with suspicion, at least when inside the controller code for a view. Nearly all the functionality available through the $scope API is better used inside of directives or services that provide a better abstraction.

- Thinking of the controller as a true constructor function instead of a function that adds stuff to $scope is healthier. You can take advantage of the constructor function prototype property to organize code, and this will work well with ES6 class definitions (which presumably will work well with ng 2.0). 

The Bad

- Writing directive controllers is different than writing view controllers. With directive controllers the instance members are often used as an API for intra-controller coordination, and this API should be separate from the model for the view.

- Somewhat related to the above, I’m still not convinced that tangling the controller and view model together is a good idea. I think there is some value in having a dedicated factory for view models.

Summary

The good appears to outweigh the bad, so I’ll switch over to using controller as syntax moving forward. I don’t think controller as is a panacea for complicated$scope code, but it does push people in a better direction.

I also think controller as  highlights the need for Angular 2.0 to make some huge, breaking changes. Once of Angular’s greatest strengths, for me, is that the framework provides enough flexibility to build a variety of apps both large and small. Routing is optional, for example, and most programming can be done with plain old JavaScript objects. However, the surface area of the framework is dangerously close to being a Mirkwood forest of programming techniques. A streamlined API with stronger opinions about how to tie components together would make the framework easier to use.

Features Of ES6 Part 2 : const

Wednesday, August 6, 2014 by K. Scott Allen
2 comments

The ES6 const keyword will give you what the keyword name implies – a read-only variable. Like let, a variable declared with const will have block scoping, and you cannot re-declare a const.

const MAX_BUNNIES = 3;

There is no requirement for a constant variable to use capital letters, that’s just a convention I like to follow.

The Significance of const

In a perfect world, all the JS runtimes would have a perfect implementation of const. Unfortunately, const is one of those keywords that has been around in some runtimes even before the keyword appeared in an official ECMAScript specification.

While most runtimes can agree that a const should be constant, existing implementations disagree on how to behave when code attempts to assign a new value to a constant. Should the assignment cause a runtime error? Should the assignment fail silently?

The ES6 specification says const should fail with a runtime error if a program tries to assign a new value to a constant, and constant declarations without an initializer should be a syntax error.

const MAX_SIZE = 10;

MAX_SIZE = 12; //SyntaxError 

I hope that it won’t take long for all the latest runtimes and browsers to straighten up and behave correctly. The current situation shouldn’t stop you from using const whenever possible because the keyword does have a few benefits.

1. const tells other programmers about the intended behavior of a variable, and this makes code easier to read.

2. const tells the runtime about the intended behavior of a variable, which can allow for small optimizations across time and space.

Coming up next: default parameters.

Want more? Watch JavaScript Fundamentals for ES6 on Pluralsight!

C# 6.0 Features Part I : Property Initializers

Monday, August 4, 2014 by K. Scott Allen
12 comments

With a new release of the C# language approaching, it’s also time to look at new features for C#.

First up is the ability to use an initialization expression with an automatically implemented property.

Currently, a constructor is required if you want to create objects using an auto-property and initialize an auto-property to a non-default value.

In C# 6.0, the ability to use an initializer with the auto-property means no explicit constructor code is required.

public class User
{ 
    public Guid Id { get; } = Guid.NewGuid();
    
    // ...
}

Another benefit of the syntax is how an initialized auto-property only requires a getter, the set method is optional. With no setter, immutability is easier to achieve.  

The property initialization syntax also plays well with another new feature for C# 6, the primary constructor syntax. We’ll look at primary constructors in the next post for this series.

The Features of ES6 Part 1: Let

Thursday, July 31, 2014 by K. Scott Allen
6 comments

The next version of ECMAScript is on the way, and I’m  genuinely excited about the changes to the JavaScript language. Thus, a series of posts with code and commentary will commence.

let: The Story

Variable scope in JavaScript has been a source of surprises and bugs over the years. The surprise is because JavaScript only offers function scope and global scope to control the lifetime of a variable. There is no block scope.

var doWork = function(flag){
    if(flag){
        var x = 3;
    }
    return x;
};

var result = doWork(true);
expect(result).toBe(3); // PASS!!!!!

The new let keyword of ES6 will replace var for variable declarations and provide true block scoping.  

var doWork = function(flag){
    if(flag){
        let x = 3;
    }
    return x; // ReferenceError: x is not defined
};

// Prepare for runtime error ...
var result = doWork(true);
expect(result).toBe(3);  

 

Iteration statements also benefit from let.

var doWork = function(){
    for(let x = 0; x < 3; x++) {
        // ...
    }
    return x; // ReferenceError: x is not defined
};

let: The Significance

The var keyword is still supported in ES6, but should be thought of as an obsolete keyword when writing ES6 code.

let is the new var!

Will let make JavaScript code better?

I doubt if let will prevent a significant number of bugs, but I do think JavaScript code will improve.

  • We can declare variables close to where they are needed instead of declaring all local variables at the top of a function, which is a defensive practice followed today to avoid var related bugs.
  • We don’t need to introduce a second nested function or IFFE only to control the scope of a variable (another defensive practice you’ll see in JS libraries).

The end result is code using let should be easier to read, and perhaps just a tiny bit safer, too. Next up we’ll look at const, and eventually move on to some of the prime movers for a paradigm shift in JavaScript programming.

Want more? Watch JavaScript Fundamentals for ES6 on Pluralsight!

Easily Generate Microsoft Office Files From C#

Wednesday, July 30, 2014 by K. Scott Allen
9 comments

It was over a decade ago when I was first asked to generate Microsoft Office files from a web application. In those days there weren’t many options available to create Office files, but for small applications it was possible to automate Office programs on the server with COM. Since Office wasn’t designed to run on a server, the automation approach always felt like climbing a frozen waterfall. From a support page:

Microsoft does not currently recommend, and does not support, automation of Microsoft Office applications from any unattended, non-interactive client application or component … because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

These days, Office files are no longer in a proprietary binary format, and are we can create the files directly without using COM automation. A .docx Word file, for example, is a collection of XML documents zipped into a single file. The official name of the format is Open XML.

There is an SDK to help with reading and writing OpenXML, and a Productivity Tool that can generate C# code for a given file. All you need to do is load a document, presentation, or workbook into the tool and press the “Reflect Code” button.

 

Document Reflector

The downside to this tool is that even a simple document will generate 4,000 lines of code. Another downside is that the generated code assumes it will write directly to the file system, however it is easy to pass in an abstract Stream object instead.

So while this code isn’t perfect, the code does produce valid document and  is useful for figuring out how the SDK classes work together. It’s also not difficult to rework the logic so the class functions as a “view”. You can pass in a model object and have the code dynamically generate a document by replacing hard coded content inside with data from the model.

Debugging AngularJS In The Console

Tuesday, July 29, 2014 by K. Scott Allen
5 comments

Although Batarang gets a lot of attention, there may come a time when you need to dig a bit deeper into an Angular application, particularly if you are debugging or spelunking someone else’s application and you aren’t familiar with the entire code base.

Here are some tricks I’ve learned.   

Find The Scope For An Element

Update: note  David Boike's comment- "When you have Batarang installed in Chrome, no need to type out angular.element($0).scope() - Batarang makes the scope of the last clicked element available in the console as '$scope'"

A non-trivial page built with Angular will have dozens of scopes containing model information for controllers, directives, transclusions, and repeaters. Although Batarang provides a clickable hierarchy of scopes on the Models tab, it’s sometimes difficult to find the exact scope you need.

Batarang showing all the models

In these scenarios I’ve found it faster to use Chrome’s $0 symbol in the developer tools console window.

You’ve never used $0? Here is an excerpt from the Chrome console documentation:

Often when testing you'll select DOM elements—either directly in the Elements panel or using the Selection tool (magnifying glass)—so that you can further inspect the element.

The Console remembers the last five elements (or heap objects) you've selected and makes them available as properties named $0, $1, $2, $3 and $4. The most recently selected element or object is available as $0, the second most as $1, and so forth.

 

Once you have an element reference, you can wrap the element with angular.element and use the scope method to retrieve the associated scope.

Using $0 to find a scope

Once you have the scope, you can drill in to see details, or take the $id property to find the scope in Batarang’s display.

Evaluate Binding Expressions

If an element has an ng-binding attribute present, you’ll find the function used to execute the binding in the data property of the element. Combine the function with a scope object or a custom object (if you want to tinker with the binding), to see what the binding function produces.

angular binding The data of an element can also hold other interesting pieces of information, like a reference to a controller.

Interact With Services

The injector method gives you access to the single injector for an application, and the injector can give you access to any service from the application. Using a service interactively allows you to play with the service, debug it, pass it strange parameters, and watch to see how it behaves.

ng services in the console

One last tip: you can always check the version of Angular a page is using by typing angular.version in the console.

Videos from NDC Oslo 2014

Monday, June 16, 2014 by K. Scott Allen
6 comments

NDC Oslo featured some fantastic content, and most of the talks are uploaded to the NDC vimeo channel.

In addition to a 2 day AngularJS workshop, I presented one session on building directives for AngularJS.

image

Also a session on using NodeJS tools for front end development (npm, Bower, Grunt, Gulp, Treceur, and more).

NodeJS Tools

I hope you like them!

by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!