【发布时间】:2016-09-13 19:55:39
【问题描述】:
Angular2 中的指令没有“范围”,而组件有。但就我而言,我需要 Directive 来创建范围。看看我的 App 组件——它有一个 HTML 模板,并且在任何元素上的任何地方都可能出现 foo 指令。这应该从服务中获取一些日期并将其分配给元素。
在 Angular1 中这很容易......指令可以有自己的范围。但在 Angular 2 中,我找不到任何(甚至是肮脏的)方法来实现这一点。
这看起来很简单,不是吗?
@Directive({
selector: '[foo]'
})
class FooDirective {
@Input()
public id:string;
public bar;
constructor() {
this.bar = 'This is the "bar" I actually need. It is taken from DB let's say..' + this.id;
}
}
@Component({
selector: 'app',
template: `
<div foo id="2">
This is random content 1: {{bar}}
</div>
<div foo id="2">
This is random content 2: {{bar}}
</div>
`,
directives: [FooDirective]
})
class App {
bar:string = 'This should be ignored, I need "bar" to be set from directive!';
}
bootstrap(App);
【问题讨论】:
标签: javascript angular angular2-directives