Thursday, October 16, 2014

Angular.js 1.3: The ng-strict-di directive

Angular.js 1.3 introduces a new directive: ‘ng-strict-di’.

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

From the documentation:

if this attribute is present on the app element, the injector will be created in "strict-di" mode. This means that the application will fail to invoke functions which do not use explicit function annotation (and are thus unsuitable for minification), as described in the Dependency Injection guide, and useful debugging info will assist in tracking down the root of these bugs.

To explain this a little bit more; Angular.js does (implicit) dependency injection based on the name of the object you try to inject. So if you specify a parameter as ‘$scope’ it will look for an object called ‘$scope’. This works great until you start using minification. When you minify your JavaScript, the function parameters are shortened to a random letter, e.g. ‘d’. When the injector runs this minifies JavaScript it no longer searches for a ‘$scope’ object, but for a ‘d’ object instead. As this object does not exists, dependency injection will fail.

A solution for this is explicitly specifying the dependencies as strings(called explicit function annotation). The ‘ng-strict-di directive’ will check if this syntax is used and throw an exception otherwise.

You can use the $inject Property annotation or use the Inline Array annotation:

3 comments:

Anonymous said...

You have a syntax error in your use of $inject.

James Coenen-Eyre said...

Legend. This is exactly what I was looking for.

Thanks for posting.
Cheers,
James

Chandra Murali said...

What is the benefit of adding ng-strict-di?