【问题标题】:Extending angularjs directives with Typescript使用 Typescript 扩展 angularjs 指令
【发布时间】:2014-09-15 18:48:14
【问题描述】:
export class MyDirective extends MyLib.directives.OtherDirective implements ng.IDirective {
  public require: string[] = ["^someReq"];
  public controller: string = "MyCtrl";
  public scope = {
    position: "@"
  };

  public static $inject: string[] = [
    '$http',
    '$q'
  ];
  constructor(
    private $http: ng.IHttpService,
    private $q: ng.IQService
  ) {
    console.log(this);  // undefined ??
    super($http: $http, $q: $q) // fails
  }

}

app.directive('myDirective', function (): ng.IDirective {
  return MyDirective
});

我的问题是双重的,上面的结构不起作用。 (我从超类收到一条错误消息:"Cannot set property 'restrict' of undefined,当它在超类的编译后的 javascript 中尝试 this.restrict = "A" 赋值时)。

我无法弄清楚为什么 this 在这种情况下是未定义的,以及为什么它不起作用。我怀疑这可能是由于我对directiveFactory 工作原理的误解。有人可以解释为什么这不起作用,并可能证明他们将如何实现我想要做的事情吗? (我知道大多数人将函数用于他们的指令,但试图从指令是一个类的库中扩展指令,所以我不确定如何使用它。

编辑:作为后续行动 - 为什么会这样?

app.directive('myDirective', ["$http",  "$q", (
    $http: ng.IQService,
    $q: ng.IQService,
  ) => {
    return new MyDirective({$http: $http, $q: $q});
  }
]);

我不喜欢它,因为您失去了 $inject 语法的好处,但为什么在这里显式调用 return new 有效?

【问题讨论】:

    标签: angularjs typescript


    【解决方案1】:

    Angular 指令 + Angular 工厂不使用 new 运算符调用。因此,您不能为它们使用类。你需要使用一个函数。这是我使用的:

    ///ts:ref=globals
    
    export interface FooDirectiveScope extends ng.IScope {
        bar: string;
    
        // Local design only
        vm: FooDirectiveController;
    }
    
    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
        }
    }
    
    dustApp.directives.directive('foo', function (): ng.IDirective {
        return {
            restrict: 'E',
            scope: {
                // NOTE : see documentation in type information
                bar: '='
            },
            templateUrl: 'fooDirective.html',
            controller: FooDirectiveController
        };
    });
    

    【讨论】:

    • 所以你不能(或不应该)在 typescript/angularjs 中扩展指令?这似乎是一个很大的限制?
    • 不,我是说你不能直接将class 用于指令,因为它不是用new 调用的
    【解决方案2】:

    最后,我选择了这个,取自here

    像这样定义一个$injection 函数:

    public static $injection(): any[] {
      return [
        '$http',
        '$q',
        ($http, $q) => new MyDirective($http, $q)
      ]
    }
    

    app.directive('rptDrawLayer', RptDrawLayer.$injection());

    它并不完美,但至少可以在缩小后幸存下来,并允许我继续使用 lib 的指令 :)

    【讨论】:

      猜你喜欢
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      • 2014-03-08
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 2016-08-30
      • 2014-03-16
      相关资源
      最近更新 更多