Typescript角度指令控制器功能

sie*_*epe 5 controller directive angularjs typescript

我有一个问题在typescript中编写angular指令.我想用typescript类编写我的指令.除控制器功能外,一切正常.

class myDirective implements ng.IDirective{

public priority :number = 999;
public require :String[] = ["ngModel","myDirective"];

public controller(){
    var test = 1;
    return {
      reset : function(){
         test = 0;
  }
    }
}

public link($scope: ng.IScope, elm: JQuery, attr: ng.IAttributes, ctrlArray: any){
    var controller;
    controller = ctrlArray[1];
    controller.reset();
}

static factory(): ng.IDirectiveFactory{
    var directive = () => new myDirective();
    return directive;
}
}
export = myDirective;
Run Code Online (Sandbox Code Playgroud)

但是当以角度运行时,当在链接函数内部调用controller.reset()时,我得到"未定义不是函数".当我检查控制器时,我只得到原型对象,没有定义复位功能.

当我这样写我的指令时,它有效.

function myDirective(): ng.IDirective{
return {
    priority: 999,
    require: ["ngModel","myDirective"],
    controller: function(){
        var test = 1;
        this.reset = function(){
            test = 0;
        }
    },
    link: function($scope: ng.IScope, elm: JQuery, attr: ng.IAttributes, ctrlArray: any){
        var controller;
        controller = ctrlArray[1];
        controller.reset();
    }
}
}
export = myDirective;
Run Code Online (Sandbox Code Playgroud)

区别在于控制器功能的编写方式.在我使用的typescript类中.

return {
      reset : function(){
         test = 0;
  }
    }
Run Code Online (Sandbox Code Playgroud)

在我使用的功能方式

this.reset = function(){
            test = 0;
        }
Run Code Online (Sandbox Code Playgroud)

不幸的是,typescript不允许我在typescript类中使用第二种方式.有什么我想念的,或者我是从错误的角度完全接近这个?

bas*_*rat 18

这是我们一直使用的指令设计:

export class FooDirectiveController {

    static $inject = ['$element', '$scope'];
    constructor(public $element: JQuery, public $scope: FooDirectiveScope) {
        $scope.vm = this;

        // Any Jquery access goes here. Use $element

        // Setup any $watch on $scope that you need
    }
}

export interface FooDirectiveScope extends ng.IScope {
    bar: string;

    // Local design only
    vm: FooDirectiveController;
}

dustApp.directives.directive('foo', function (): ng.IDirective {
    return {
        restrict: 'E',
        scope: {
            // NOTE : see documentation in type information
            bar: '='
        },
        templateUrl: 'fooDirective.html',
        controller: FooDirectiveController
    };
});
Run Code Online (Sandbox Code Playgroud)

这样,您的控制器是强类型的,并且指令定义对象是哑的(并且可能与角度2兼容).