ceth
ceth

Reputation: 45295

Create AngularJs controller using TypeScript

I have JS code with Angular controller which starts like this:

angular.module('myApp.controllers', [])
    .controller('BookmarksController', function($scope, bookmarkService, crawlerService) {

I want to rewrite it using TypeScript. Here is my code:

class Some {

    constructor($scope, bookmarkService, crawlerService) {} 
}

angular
    .module('myApp.controllers', [])
    .controller('BookmarksController', Some($scope, bookmarkService, crawlerService));

It doesn't work:

Can not find name $scope, bookmarkService, crawlerService

How can I fix it ?

Upvotes: 1

Views: 503

Answers (1)

Radim Köhler
Radim Köhler

Reputation: 123861

The best way (well, solution ready for minification) would be:

class Some {
    // instruction for IoC
    static $inject = ["$scope", "bookmarkService", "crawlerService"];

    constructor($scope, bookmarkService, crawlerService) {} 
}

angular
    .module('myApp.controllers', [])
    .controller('BookmarksController', Some);

Where we are using the static $inject = [] array for IoC names, which will work even after minification. Then we just register the controller class

.controller('BookmarksController', Some);

and later angular IoC will properly find out what should be injected as constructor params

In case we would use some modules/namespaces

module My.Namespace
{
    class Some {

we would use:

.controller('BookmarksController', My.Namespace.Some);

Upvotes: 2

Related Questions