如何将 angularJS 指令转换为 Typescript?

How can I convert angularJS directive to Typescript?

大家好,我需要一个指令。那应该设计为十进制数字。我找到了我想要的。但是我的项目中没有 运行 这段代码。

我正在使用:

ionic (Ionic CLI) : 4.2.1

这是代码:

  app.directive('salary', function(){
  return {
      restrict: 'E'
      , scope: {
          salary: '@'
      }
      , controller: controller
      , controllerAs: 'dvm'
      , bindToController: true
      , template: '<h2><sup>$</sup>{{ dvm.dollar }}<sub>.{{ dvm.cents }}</sub></h2>'
  };

  function controller(){
    var parts = parseFloat(this.salary).toFixed(2).split(/\./);
    this.dollar = parts[0];
    this.cents = parts[1];
  }
});

plunker

感谢您的帮助!

因为你有一个带有模板的指令,可以用选择器标签显示在 UI 中,因此你可以在 Angular 6(或任何更大的东西)中使用等效的 Component比 2x 版本)。这是 typescript/Angular 6

中的等效代码

salary.component.ts

import { Component ,OnInit} from '@angular/core';

@Component({
  selector: 'salary',
  templateUrl: './salary.component.html'
})
export class SalaryComponent  implements OnInit{
  salary:string = "9033";
  dollar:string; 
  cents:string;
  ngOnInit(){
    let parts = parseFloat(this.salary).toFixed(2).split(/\./);
    this.dollar = parts[0];
    this.cents = parts[1];
  }

}

salary.component.html

<h2><sup>$</sup>{{ dollar }}<sub>.{{ cents }}</sub></h2>

用法

<salary></salary>

如果你想动态设置薪水的值,那么你需要使用 @Input() 装饰器来设置父组件的 属性 的值,如下所示 -

@Input() formattedSalary:string = "";

并在 HTML 中使用它,例如 -

<salary [formattedSalary]="9033"></salary>

这是 Angular 6

中的一个工作示例

https://stackblitz.com/edit/hello-angular-6-tagnx9