0

In new version of angular you must define controller like this

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
});

How can I define This code by TypeScript?

2

1 Answer 1

2

Controller will be something like:

class myCtrl
{
  constructor( $scope )
  {
    $scope.firstName = "John";
    $scope.lastName = "Doe";
  }
}

And with module it will be something like

module myApp{

    export class myCtrl{

     static $inject = ["$scope"];

        constructor( $scope: any)
      {
        $scope.firstName = "John";
        $scope.lastName = "Doe";
      }
    }
}

$inject method specify the parameters that angular will inject in the class constructor. like $scope in our example you can inject services etc also

Now you can use it as

angular.module('myApp', []).controller('myCtrl',myApp.myCtrl);
Sign up to request clarification or add additional context in comments.

6 Comments

What about $scope injection?
@estus is it right now? plz improve it if i am missing something as i am also learning 2.0 and typescript
@A.B tnx...Can you explane about static $inject = ["$scope"]; in your answer
@A.B I have an build error on this line "angular.module('myApp', []).controller('myCtrl',myApp.myCtrl);" that say "Could not find symbol 'angular'"...I add this line in TypeScript File
add angular-mocks.d.ts and then try
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.