【问题标题】:AngularJS bindings with Typescript and ng.IComponentControllerAngularJS 与 Typescript 和 ng.IComponentController 的绑定
【发布时间】:2023-03-28 06:01:02
【问题描述】:

我正在使用带有 Babel 和 Typescript 的 webpack

我有这个控制器:

// HelloWorldController.ts

class HelloWorldController implements ng.IComponentController {

constructor(private $scope: ng.IScope) {
}

public over(): void {
    this.$scope.color = this.change();
}
}

和他的组件选项

export class HelloWorldComponent implements ng.IComponentOptions {

public bindings: {[binding: string]: string};
public controller: Function;
public templateUrl: string;

public constructor() {
    this.bindings = {
        color: '=',
        change: "&"
    };
    this.controller = HelloWorldController;
    this.templateUrl = "HelloWorld.html";
    }
}
app.component('helloWorld', new HelloWorldComponent());

当我转译这段代码时,我得到了这个错误:

error TS2339: Property 'change' does not exist on type 'HelloWorldController'

如何使用 Typescript 访问控制器内的绑定引用?

【问题讨论】:

    标签: angularjs typescript webpack babeljs


    【解决方案1】:

    您需要在控制器上声明绑定变量:

    // HelloWorldController.ts
    class HelloWorldController implements ng.IComponentController {
    
        change: () => any;
        color: any;
    
        public over(): void {
            this.color = this.change();
        }
    }
    

    这样,你告诉 TypeScript 你的控制器上存在这些属性。

    请注意,在初始化组件控制器期间,Angular 将应用您在组件选项 (color: '=', change: "&") 中设置的绑定,并将控制器的变量设置为其绑定值。这意味着您不必再通过 $scope 访问这些绑定(就像在 over 方法中所做的那样),这完全消除了将 $scope 注入控制器的需要并大大提高了可重用性你的代码。

    【讨论】:

      猜你喜欢
      • 2014-10-05
      • 1970-01-01
      • 2016-02-10
      • 2013-06-07
      • 1970-01-01
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多