Angular JS组件绑定
我无法将项目从父组件的ng-repeat循环到可用的嵌套组件的作用域。父组件是一个包含许多项目组件的传送带。传送带由ng-repeat填充。我希望能够访问项目控制器(“it”)中的传送带控制器(“cr”)的“项目”和方法。我想我正在以完全错误的方式解决这个问题。感谢有人能给我一个指导。Angular JS组件绑定
carousel.component.html
<slick <!--slick attributes--> >
<div ng-repeat="item in cr.items">
<item-component></item-component>
</div>
</slick>
carousel.component.js
class CarouselController{
constructor(/*stuff*/){
'ngInject';
this.items =[
{"something":"The thing 1","otherthing":"The other thing 1"},
{"something":"The thing 2","otherthing":"The other thing 2"},
{"something":"The thing 3","otherthing":"The other thing 3"}
];
}
parentFunctionToCall(item){
console.log('I called a function on the parent!',item)
}
/*other stuff*/
}
export const CarouselComponent = {
templateUrl: './views/app/components/carousel/carousel.component.html',
controller: CarouselController,
controllerAs: 'cr',
bindings: {
}
}
item.component.html
<div data-something="{{item.something}}">
Yo,{{item.otherthing}}!
</div>
<a href="#" ng-click="cr.parentFunctionToCall(item)">
Trying to call a function on the parent component
</a>
item.component.js
class ItemController{
constructor($scope,/*stuff*/){
'ngInject';
//$scope.it.item & $scope.it.cr are both undefined
console.log(this);
//I understand this is the incorrect way but it works
this.$scope.item = this.$scope.$parent.item;
console.log(this);
}
/*other stuff*/
}
export const ItemComponent = {
templateUrl: './views/app/components/carousel/item.component.html',
controller: ItemController,
controllerAs: 'it',
bindings: {
"item":"=",//i can see this as undefined $scope in ItemController
"cr":"=" //i want to access a method on the parent controller
}
}
这说明怎么了...... https://plnkr.co/edit/UG20EtI4KxnVnTe8zzz4?p=preview
最终无奈的简单..我不知道为什么这个心不是做的文档更清晰,但其作为子组件上设置一个属性一样容易:
<slick <!--slick attributes--> >
<div ng-repeat="item in cr.items">
<!--new item="item" attr-->
<item-component item="item" call-parent="cr.parentFunctionToCall(item)"></item-component>
</div>
</slick>
然后,绑定按预期工作。在父级*问函数的行为方式类似。某些事件名称需要添加为属性(call-parent
,但这可以是任何内容)。的结合需要被添加到子组件(如@kuhnroyals评论):
...
bindings: {
item:"=",
callParent: '&'
}
而且ng-click="it.callParent()"
工作示例这里的子组件如一些互动事件:https://plnkr.co/edit/RIOPs6?p=preview
您可以使用'&'绑定以相同的方式绑定一个函数。 'onDelete'和'onUpdate'就是例子。 – kuhnroyal
@kuhnroyal非常感谢 –
使用controllerAs
你没有一个$scope
,你需要使用this
。特别是与组件。
this.items =[
{"something":"The thing 1","otherthing","The other thing 1"},
{"something":"The thing 2","otherthing","The other thing 2"},
{"something":"The thing 3","otherthing","The other thing 3"}
];
谢谢 - 编辑。仍然没有收到父母的东西 –
你没有父母的范围,他们总是孤立的范围。查看链接。您可以要求父控制器并注入它。 – kuhnroyal
是的,我明白了,但我认为通过绑定,我应该能够从父元素(即带有ng-repeat的div)向ng-repeat内的'item-component'提供范围。当然,这可以以某种方式,而不用做哈克东西访问'$范围。$ parent.item'(它工作,但击败了孤立的范围想法)参考文档 –
请更新您的代码到一个工作片段,我很乐意看看。 –
@PhilPoore传入,非常感谢 –
@PhilPoore如果您的报价仍然存在 - https://plnkr.co/edit/UG20EtI4KxnVnTe8zzz4?p=preview –