目前,正在尝试以Angular2风格编写代码,即不使用控制器。面临着从外部和内部指令传递数据的问题。如何正确操作?主要问题是指令内部如何访问外部范围并使用内部指令模板中的数据?实例在代码笔上
<test-directive>
<nested/>
</test-directive>
我已经简化了代码笔,请参阅我的修改版本。
class Nested {
restrict='E';
template='<p>Nested {{inner.outer}} {{inner.last}}</p>';
controller=function(){
this.last='Pupkin';
};
controllerAs='inner';
bindToController={
outer: '=' // a communicating point of outer and inner directives
};
}
关键是,在bindToController
中,您可以添加端点变量,此处为outer
。在外部模板中,给它一个值,如:<nested outer="outer.first"/>
。
@Günter Zöchbauer的答案是关于Angular 2。
此外,如果你想看到一个使用Anguar1组件风格的完整例子,你可以看到我的express-angular-es6-starter,一个使用es6和组件风格angular 1代码的todo mvc。
您需要显式地传递值
<test-directive>
<nested [someInput]="somePropertyOnParent"></nested>
</test-directive>
@Component({
selector: 'nested',
template: `<ng-content></ng-content>`)}
class Nested {
@Input() someInput;
ngOnInit() {
console.log(this.someInput);
}
}