Angular JS组件绑定

时间:2017-01-09 19:23:52

标签: javascript angularjs binding

我无法使项目从可用于嵌套组件范围的父组件的ng-repeat循环。父组件是包含许多项组件的轮播。旋转木马由ng-repeat填充。我希望能够访问"项目"以及项目控制器中的轮播控制器(" cr")的方法(" it")。我猜我会以完全错误的方式解决这个问题。感谢是否有人可以给我一个转向。

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

2 个答案:

答案 0 :(得分:1)

使用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"}
 ];

请参阅https://jsfiddle.net/494wrsyo/2/

答案 1 :(得分:0)

最终令人沮丧的简单..我不确定为什么这在文档中没有更明确,但它就像在子组件上设置属性一样简单:

<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