【问题标题】:How can I convert angularJS directive to Typescript?如何将 angularJS 指令转换为 Typescript?
【发布时间】:2019-03-19 02:11:38
【问题描述】:

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

我正在使用:

离子(离子 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

感谢您的帮助!

【问题讨论】:

  • Yilmaz 检查我对 Angular 6/typescript 中等效代码的回答。
  • 您应该正确地将 Angular JS 指定为 Angular(typescript),而不是 Angular JS 指定为 typescript。您也可以在 typscript 中编写 Angular js 代码。
  • 嘿@jameelM 感谢您的评论。我是角度和离子的新手。那是我的错。

标签: angularjs angular typescript angularjs-directive ionic4


【解决方案1】:

由于您有一个带有模板的指令,该指令可以使用选择器标记显示在 UI 中,因此您可以在 Angular 6(或任何大于 2x 的版本)中使用等效的 Component。这是 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>

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

@Input() formattedSalary:string = "";

并在 HTML 中使用它,例如 -

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

这是 Angular 6 中的一个工作示例

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

【讨论】:

  • OP 要求 angularJS 不是 angular。
  • @JameelM 在 typescript 中提到过,所以 OP 需要确认 Angular 或 Angularjs 是必需的
  • 检查他的标签和源代码的语法。您也可以使用 typescript 编写 angular js。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-22
  • 1970-01-01
相关资源
最近更新 更多