Define AngularJS directive using TypeScript and $inject mechanism

后端 未结 9 1709
死守一世寂寞
死守一世寂寞 2020-12-12 15:04

Recently I started refactoring one of the Angular projects I am working on with TypeScript. Using TypeScript classes to define controllers is very convenient and works well

9条回答
  •  一向
    一向 (楼主)
    2020-12-12 15:35

    This answer was somewhat based off @Mobiletainment's answer. I only include it because I tried to make it a little more readable and understandable for beginners.

    module someModule { 
    
        function setup() { 
            //usage: 
            angular.module('someApp').directive("someDirective", someDirective); 
        };
        function someDirective(): ng.IDirective{
    
            var someDirective = {
                restrict: 'E',
                templateUrl: '/somehtml.html',
                controller: SomeDirectiveController,
                controllerAs: 'vm',
                scope: {},
                link: SomeDirectiveLink,
            };
    
            return someDirective;
        };
        class SomeDirectiveController{
    
            static $inject = ['$scope'];
    
            constructor($scope) {
    
                var dbugThis = true;
                if(dbugThis){console.log("%ccalled SomeDirectiveController()","color:orange");}
            };
        };
        class SomeDirectiveLink{
            constructor(scope: ng.IScope, element: ng.IAugmentedJQuery, attributes: ng.IAttributes, controller){
                var dbugThis = true;
                if(dbugThis){console.log("%ccalled SomeDirectiveLink()","color:orange");}
            }
        };
        setup();
    }
    

提交回复
热议问题