Search code examples
javascriptangularjstypescriptangular-directiveangular-controller

How to Add Controller In Angular Directive Class In Typescript


Following is my angular directive class in typescript I have written so far:

My question is how I can add controller for this directive. I don't want to create new controller class and bind that controller with controller. I want to write the controller and inject the ISOLATE SCOPE inside the directive class in typescript

    module Sheet.Directive{
    class InputControl implements ng.IDirective {
    restrict = 'A';
    //require = 'ngModel';
    templateUrl = "../Templates/inputcontrol.html";



    constructor(private $location: ng.ILocationService) {
    }

    link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ctrl: any) => {
        console.log(this.$location);
    };

    static factory(): ng.IDirectiveFactory {
        const directive = ($location: ng.ILocationService) => new InputControl($location);
        directive.$inject = ['$location'];
        return directive;
    }
}

angular.module("SheetApp").directive("inputControl", InputControl.factory());
}

Solution

  • You can actually declare property controller that will return a controller function, like:

    export class App {
      restrict='E';
      templateUrl='src/app.html';
      scope = {
        a : '@'
      }
      controller = ['$scope',($scope) => {
        console.log("this this controller",$scope.a);
      }];
    }
    

    Here is example in Plunker: http://plnkr.co/edit/j4coAAZ207RHyGsqFPgC (I used my @directive trick for more convinient declaration of directives.