0

I am rewriting my AngularJS application using TypeScript. In my application I have used $scope to define variables and methods:

defectResource.defectByDefectId($scope.defectid).then(function (data) {
   $scope.defect = data;
});

$scope.postDefect = function () {
   defectResource.postDefect($scope.defect).then(function () {
      $location.path('defects/' + $stateParams.itemid);
   });
};

I can rewrite my controller something like this:

interface IDefectDetailModel {
}

class DefectDetailController implements IDefectDetailModel {
    static $inject = ['$scope', '$stateParams', '$location', 'defectResource', 'entityProvider'];

    constructor($scope: any, $stateParams: any, $location: any, defectResource: any, entityProvider: any) {
       defectResource.defectByDefectId($scope.defectid).then(function  (data) {
          $scope.defect = data;
       });

      $scope.postDefect = function () {
        defectResource.postDefect($scope.defect).then(function () {
           $location.path('defects/' + $stateParams.itemid);
        });
      };
    }
}

But if I understood correctly it is not good way. I need to create Interface and TypeScript class which will implement this interface. All my variables must be class variables (so $scope.defectid must be this.defectid) and all my $scope methods must be class methods (this.postDefect()).

Do I understood correctly? If I am using AngularJS with TypeScript the best way is not use $scope variables and methods and use only instance variables and methods (using this) ?

1 Answer 1

2

If I am using AngularJS with TypeScript the best way is not use $scope variables and methods and use only instance variables and methods (using this) ?

+100.

Key reason being that scope variables are susceptible to become disconnected due to angular's scope inheritance mechanism. Even without TypeScript it is recommended not to use scope varaibles and this is why the controller as syntax was created.

More on Angular controllers in typescript: https://www.youtube.com/watch?v=WdtVn_8K17E

Sign up to request clarification or add additional context in comments.

Comments

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.