【问题标题】:How to bind attributes in an Angular directive using TypeScript?如何使用 TypeScript 在 Angular 指令中绑定属性?
【发布时间】:2016-03-02 18:26:36
【问题描述】:

使用 AngularJS 1.5 和 TypeScript 我正在编写一个指令,并希望在我的视图中定义一个属性,该属性被传递到指令中,然后用于输出到模板。我尝试遵循一些示例,例如this one,但我的指令模板未绑定到该属性。

来自页面的 HTML:

<my-directive name="John"></my-directive>

指令:

module myApp.directives {
    "use strict";

    export class myDirective {
      static directiveId = 'myDirective';
      scope = {};
      bindToController = {
        name: '='
      };
      restrict = 'EA';
      controller = controllers.NameController.ControllerId;
      controllerAs = 'vm';
      template = '<h1>Name: {{ vm.name }}</h1>';

      static $inject = [];
      constructor() { }

      static instance() {
        return new myDirective();
      }
    }
    angular.module("myApp").directive(myDirective.directiveId, myDirective.instance);
}

控制器(不确定我是否需要在构造函数中添加任何内容?):

module myApp.controllers {
    "use strict";

    export class NameController {
        static ControllerId = "NameController";
        name: string;

        constructor(name: string){
            this.name = name;
        }
    }

    angular.module("myApp").controller(NameController.ControllerId, NameController);
}

【问题讨论】:

    标签: angularjs angularjs-directive typescript


    【解决方案1】:

    你的 bindToController 应该接受一个字符串,而不是一个绑定的属性,即

    bindToController = { name: '@' };

    = 将尝试在您的语法中评估一个名为 John 的属性,该属性不存在。

    另外,你的构造函数不需要任何参数,我看到的可以完全删除。

    【讨论】:

      【解决方案2】:

      我不确定这是否有帮助,角度如何将 NameController 和 $scope 的实例合并在一起,但我可以想象 NameController 实例的 name 属性正在遮蔽 $scope.name。

      你会尝试删除:

      name: string;
      
      constructor(name: string) {
        this.name = name;
      }
      

      ?

      【讨论】:

      • 当我删除它时,我的视图从显示“名称:{{ vm.name }}”(大括号可见)变为“名称:”(没有大括号但也没有数据)。跨度>
      【解决方案3】:

      我相信您需要的属性应该在指令范围内定义,因为您已经在使用隔离范围。您似乎没有在任何地方使用bindToController。

      而不是这个:

      scope = {};
      bindToController = {
        name: '='
      };
      

      试试这个(旧语法):

      scope = {
        name: '='
      };
      

      此外,控制器中的参数化构造函数不会运行,因为您没有 new-ing 类(在下面的行中,来自您的第二个代码 sn-p)

      angular.module("myApp").controller(NameController.ControllerId, NameController);
      

      【讨论】:

        猜你喜欢
        • 2018-12-07
        • 2016-11-04
        • 2016-04-04
        • 1970-01-01
        • 1970-01-01
        • 2021-05-21
        • 1970-01-01
        • 2017-02-14
        • 2019-04-08
        相关资源
        最近更新 更多