AngularJS in TypeScript: Dependency Injection

In this article, I want to continue what I wrote previously about AngularJS and TypeScript. Based on the code on my GitHub, I'll show different ways to inject dependencies using TypeScript

As mentioned in AngularJS doc, there are three ways to do injection:
1. Implicit Dependencies
2. $inject property annotation
3. Inline Array annotation

I'm not gonna show how to do Implicit Dependencies, as it's something that's not recommended to do.

$inject property annotation
module Test {
    export class Abc{
        static $inject = ['$scope', '$rootScope'];          
        constructor($scope, $rootScope){                
        }
    }
}    
app.controller('abc', Test.Abc);

Basically, I just need to declare $inject as static property in the class.
The full sample is available in this code

Inline array annotation
module Test {
    export class Abc{      
        constructor($scope, $rootScope){
        }

        public static Init($scope, $rootScope){
            return new Abc($scope, $rootScope);
        }
    }
}    
app.controller('abc', ['$scope', '$rootScope', Test.Abc.Init]);

As you can see, I call the static function in the inline Array. Then, that static function will return the Object.
The full sample is available in this code

Both are working fine for me. But personally, I prefer $inject property annotation, because it looks confusing when there are quite a lot of dependencies

Abdurrachman Habibi

Read more posts by this author.