Automate Angular’s Strict DI

When working with Angular JS you might have come to investigate strict-di and what can be done in order to ensure your application still functions properly after minification.

Basicly, in order for Angular to work after minification, we need to explicitly annotating the particular function using either the inline bracket notation or using the $inject property.

 function GoodController1($scope, $http, $filter) {
     // ...
 }
 GoodController1.$inject = ["$scope", "$http", "$filter"]`;

 angular.module('myApp', [])
     // Register the function which uses the $inject property
   .controller("GoodController1", GoodController1)
     // Register the function with inline bracket notation
   .controller("GoodController2", [
     "$scope",
     "$http",
     "$filter",
     function($scope, $http, $filter) {
       // ...
     }
 ]);

As this can easily be forgotten we can enforce strict-di by adding the ng-strict-di directive to the same element as the ng-app directive, resulting in runtime exceptions when using functions without explicit anotation.

 <html ng-app="myApp" ng-strict-di>

If you prefer (or have the need to) bootstrap your application manually, you can provide strictDi: true in the optional config argument.

 angular.bootstrap(document, ['myApp'], {
   strictDi: true
 });

If you now add the following controller, a runtime exception will occur:

 angular.module("myApp", [])
     .controller("GoodController2", function($scope, $http, $filter) { }
 ]);

Alright, so we know about strict-di and what we need to take into account to ensure a proper working application.
But doesn’t all of this add a lot of overhead to developing Angular applications? Every function which needs to use the Angular DI needs to be explicitly annotated using one of the two approaches, that’s way to much typing, I’m to lazy for that.

Automation FTW

The explicit annotation using the $inject property is the one that can be automated the easiest as it’s always the exact same thing:

  • Take the function’s parameter names
  • Put them in an array as strings
  • Assign the array to the function’s $inject property

It wouldn’t take a lot effort to write a script to do this for us, right ?
However, it’s even cooler because there are existing grunt and gulp tasks, respectivly grunt-ng-annotate and gulp-ng-annotate, both based on ng-annotate

Configuring gulp-ng-annotate

The plugin’s github page pretty much explains it all decently. However, as I prefer my posts to be complete I include a sample on how to get started:

 var gulp = require('gulp');
 var ngAnnotate = require('gulp-ng-annotate');

 gulp.task('default', function () {
     return gulp.src('src/app.js')
         .pipe(ngAnnotate())
         // minification etc
         .pipe(gulp.dest('dist'));
 });

As you can see, ngAnnotate() should be called somewhere inside your JavaScript build task, before minification and moving the sources to a specific destination (dist).

Configuring grunt-ng-annotate

First of all, I don’t like grunt. I’m sorry. This is personal and I won’t claim grunt to be bad, I just don’t like it’s syntax. If you do, fine … Keep using grunt as there is no reason to switch over if you like Grunt.

 grunt.initConfig({
     ngAnnotate: {
         dist: {
             files: [{
                 expand: true,
                 cwd: '.tmp/concat/scripts',
                 src: '*.js',
                 dest: '.tmp/concat/scripts'
             }]
         }
     },
 }

Just as with using gulp, when using grunt you have to ensure ngAnnotate is called before minification.

So now we all can stop waisting time with manually annotating functions when doing Angular development and focus on the cool things by providing the ‘ngInject’ string as first line in each method that requires to be annotated!

 function GoodController1($scope, $http, $filter) {
    'ngInject';
     // ...
 }

 angular.module('myApp', [])
   .controller("GoodController1", GoodController1)
   .controller("GoodController2", function($scope, $http, $filter) {
       'ngInject';
       // ...
     });

Decoupled from the configuration file

When working on a variaty of projects, we always come across a situation where we need to use configurable settings stored in a web.config / app.config file.
Accessing settings from the web.config is made easy using the ConfigurationManager class. However, sometimes I see this class floating around the entire application, making it hard to keep track of all the settings or eventualy even move one of these settings to a different configuration file.

Continue reading…

ExpressJS MVC application – Handlebars views

In the previous post we’ve seperated our controller logic from the express configuration.

The second part of MVC we’re going to deal with is the View, more specificly we are going to integrate handlebars as a view engine in expressjs.

Handlebars provides the power necessary to let you build semantic templates effectively with no frustration.
Handlebars is largely compatible with Mustache templates. In most cases it is possible to swap out Mustache with Handlebars and continue using your current templates. Complete details can be found here.

Continue reading…

ExpressJS MVC application – Seperating Controller

In my previous post, I’ve been explaining the basics to create an application with ExpressJS. In this post I’ll be showing how to seperate the controllers from the entry file (app.js).

When developing maintainable applications It’s a bad idea to put everything in a single file, therefor it’s advised to seperate files based on there concerns (Seperation of Concerns principle).

Continue reading…

Manual caching using the decorator pattern

For performance reasons it’s a good idea to keep caching in mind, however it can be difficult to implement in such a way that you can still work without caching or even switch between different types of caching (memory, http) in no time.
As always, I think it’s a great idea to control everything using any inversion of control container, that’s what it should be used for anyway!

Before I continue, I would like to mention the existence of several frameworks which handle caching for you. This article is for those who prefer to handle caching without a specific framework. Whether it’s better to use a framework or not is not part of this post.

Continue reading…

KnockoutJS

Getting to know Knockout JS

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably

Let’s take a small html application to demonstrate how KnockoutJS can speed up your development progress.

Continue reading…

The static anti pattern

In my very young development carreer I’ve met way to many people who like to abuse the static keyword. Both static classes and static methods are evil, for the reason that using it looks like making your life alot easier but it actually does not. It also takes some knowledge to known when to use it and when not.

I’m not the person who knows all about statics, but I do know some situations where static classes and methods can break your entire application.

People tend to like statics for the main reason there is no requirement to initialize a new object each time. E.g. PrintService.Print(string someMessage) could be a static method and you can easily access it from anywere. I agree with them that having alot of object initializations inside a class is bad, but replacing them by statics is not the solution since the class’ keeps coupled to the specific logic and therefor you are not removing the problem at all.

Continue reading…

Netduino

Introduction to Netduino

Some time ago I decided I wanted to get back into some electronic development, which was part of my education. I came across Netduino, an open-source electronics platform using the .NET Micro Framework. How much cooler could it get? Electronics development using .NET, that really was what I needed!

According to http://www.netmf.com., the .NET Micro Framework is an open source platform that expands the power and versatility of .NET to the world of small embedded applications. Desktop programmers can harness their existing .NET knowledge base to bring complex embedded concepts to market on time (and under budget). Embedded Developers can tap into the massive productivity gains that have been seen on the Desktop.

Continue reading…

ninject

Dependency Injection in a WPF MVVM application using Ninject

I’ve been working with ASP.NET MVC for awhile now, but recently I’ve had the chance to work on a WPF project. It has been since college that I have worked on an XAML based application.

Since I have found Dependency Injection to be more and more interesting due to the improvement of testability, I immediatly started wondering how this can be used with WPF applications for it to be more and more interface oriented.

I started exploring the View-First approach first, I might get into the ViewModel-first later. I consider the reader of this post to be familiar with the MVVM pattern.

Continue reading…