0

我正在开发一个使用AngularJS 1.5.7开发的旧项目。我想为新开发的东西使用TypeScript。所以只有新增的东西应该在TypeScript中 - 目前没有完全迁移。在TypeScript上优化AngularJS 1.5.7指令 - ...参数不工作,封装了2个类

我能够找到如何在AngularJS上用TypeScript编写指令。

import * as angular from 'angular'; 

angular 
    .module('starter.directives') 
    .directive('lateralScrollbar', ['$timeout', ($timeout) => 
     new (class { 
      restrict = 'A'; 

      constructor(
       private $timeout 
      ) { } 

      link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) { 
       let directive = this; 

       new (class { 
        constructor(
         scope: ng.IScope, 
         element: ng.IAugmentedJQuery, 
         attrs: ng.IAttributes 
        ) { 
         scope.something = 'Loading'; 
         /** 1. How to optimize hat "directive" is not needed here? Maybe that I can use "this" instead or "parent" */ 
         directive.$timeout(() => scope.something = 'OK', 1000); 
        } 
       })(scope, element, attrs); 
      } 
      /** 2. How to optimize that I can pass the arguments with that the function was called. For example fn.apply(); and ...args? */ 
     })($timeout) 
    ]); 

您可以看到有2条评论。

  1. 如何优化帽子“指令”在这里不需要?也许我可以使用“this”代替或“父”
  2. 如何优化我可以传递函数被调用的参数。例如fn.apply();和...参数?

所以第一个很有趣。我认为。目前,我尽可能地使用一系列依赖和函数来调用该指令。这个函数在其中创建了一个类的对象,然后这个类有一个链接函数,它定义了directivethis,这样我就可以使用传入的参数(即$ timeout )

第二件事是我定义了$timeout变量4次在Angular指令的依赖关系1 x类的构造函数1 x参数用于第一类初始化1 x in这是第一类包装的功能

所以这是我的一个尝试,但它失败了,因为它不能处理这个...args事情。不知道如何优化。

import * as angular from 'angular'; 

angular 
    .module('starter.directives') 
    .directive('lateralScrollbar', ['$timeout', (...args) => 
     new (class { 
      restrict = 'A'; 

      constructor(
       private $timeout 
      ) { } 

      link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) { 
       let directive = this; 

       new (class { 
        constructor(
         scope: ng.IScope, 
         element: ng.IAugmentedJQuery, 
         attrs: ng.IAttributes 
        ) { 
         scope.something = 'Loading'; 
         /** 1. How to optimize hat "directive" is not needed here? Maybe that I can use "this" instead or "parent" */ 
         directive.$timeout(() => scope.something = 'OK', 1000); 
        } 
       })(scope, element, attrs); 
      } 
      /** 2. How to optimize that I can pass the arguments with that the function was called. For example fn.apply(); and ...args? */ 
     })(args) 
    ]); 

错误:TS2554:预计1个参数,但0

也许有人可以帮我:-)感谢在前进!

回答

0

使用类型脚本,首先必须使用类创建指令,然后必须通过类的工厂方法将类声明为角度应用程序指令。

查看下面的参考链接以便更好地理解。

Reference 1 Reference 2