【问题标题】:Typescript angular directive controller function打字稿角度指令控制器功能
【发布时间】:2015-04-16 06:42:25
【问题描述】:

我在打字稿中编写角度指令时遇到问题。 我想使用打字稿类编写我的指令。除控制器功能外,一切正常。

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;

但是当以角度运行时,当在链接函数中调用 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;

区别在于控制器函数的编写方式。在我使用的 typescript 类中。

return {
      reset : function(){
         test = 0;
  }
    }

在我使用的函数方式中

this.reset = function(){
            test = 0;
        }

不幸的是,打字稿不允许我在打字稿类中使用第二种方式。有什么我遗漏的吗,还是我完全从错误的角度来解决这个问题?

【问题讨论】:

  • 我认为你可以这样做 this.reset => { this.test = 0};在测试脚本中。

标签: angularjs controller typescript directive


【解决方案1】:

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

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
    };
});

这种方式你的控制器是强类型并且指令定义对象是哑的(并且可能兼容 angular 2)。

【讨论】:

  • 谢谢,这似乎可以解决问题。知道为什么其他代码不起作用吗?
  • github.com/angular/angular.js/blob/v1.4.7/src/ng/… 这行就是原因。该函数以javascript fn.apply(null, arguments) 调用因此,在此上下文中 this 变为 null。
猜你喜欢
  • 2015-07-19
  • 2017-02-15
  • 2016-04-27
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 2013-12-28
  • 2016-09-07
  • 2015-01-29
相关资源
最近更新 更多