Angularjs。嵌套指令中的继承范围
Angularjs. Inheritance scope in nested directive
目前,正在尝试以 Angular2 风格编写代码,即不使用控制器。面临来自外部指令和内部指令的数据传输问题。如何正确地做到这一点?
主要问题是指令内部如何访问外部范围并使用内部指令模板中的数据?例子
on codepen
<test-directive>
<nested/>
</test-directive>
您需要明确传递值
<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);
}
}
我已经简化了你的codepen,看我修改的version。
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.
另外,如果你想看一个完整的使用 Angualr 1 组件风格的例子,你可以看我的 express-angular-es6-starter,A todo mvc with ES6 and component style Angular 1 codes.
目前,正在尝试以 Angular2 风格编写代码,即不使用控制器。面临来自外部指令和内部指令的数据传输问题。如何正确地做到这一点? 主要问题是指令内部如何访问外部范围并使用内部指令模板中的数据?例子 on codepen
<test-directive>
<nested/>
</test-directive>
您需要明确传递值
<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);
}
}
我已经简化了你的codepen,看我修改的version。
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.
另外,如果你想看一个完整的使用 Angualr 1 组件风格的例子,你可以看我的 express-angular-es6-starter,A todo mvc with ES6 and component style Angular 1 codes.