2016-03-02 63 views
0

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

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); 
} 

回答

2

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

bindToController = { name: '@' };

=将试图评估一个名为John在你的语法属性,它不存在。

此外,您的构造函数不需要任何参数,而对于我所看到的可以完全删除。

+0

谢谢!这解决了我的问题。 –

+0

不客气! –

0

我不知道这有助于,既没有角度合并NameController的实例和$范围在一起,但我可以成像的名称属性NameController实例映射$ scope.name。

你会尝试删除:

name: string; 

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

+0

当我删除它时,我的视图改变m“Name:{{vm.name}}”(大括号可见)显示为“Name:”(没有大括号,也没有数据)。 –

0

我相信你需要的属性应该在指令作用域上定义,因为你已经在使用独立作用域了。看起来不像你在任何地方使用bindToController

取而代之的是:

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

尝试用这种(旧的语法):

scope = { 
    name: '=' 
}; 

此外,在控制器的参数的构造函数将无法运行,因为你不是new -ing起来该类(在下面的行中,从您的第二个代码片段)

angular.module("myApp").controller(NameController.ControllerId, NameController); 
相关问题