2016-09-22 190 views
1

我想从父组件传递一个函数给子组件,并给它一个从父组件给孩子的参数。 (showOrHideSub =“item.showOrHideSub(item.id)”)我尝试过不同的方法,它不起作用。如何将参数传递给组件?

这是我想要使用子组件标记的html(父组件)。 vm是此范围的控制器:

<li ng-repeat="item in vm.menuItems"> 
<menu-item-comp id="item.id" showOrHideSub="item.showOrHideSub(item.id)" /> 
</li> 

以下是子组件模板。 itemVm是这个组件的控制器:

<div id="{{itemVm.id}}" ng-mouseover="itemVm.showOrHideSub(itemVm.id)"> 
<div id="itemVm.subId" class="menuItemImgText">{{ itemVm.label }}</div> 

这里是子组件JS:

module.component('menuItemComp', { 
     templateUrl: '/webapp/app/components/menu/menuItemComponent.html', 
     bindings: { 
      id: '<', 
      showOrHideSub: '&', 
      label: '<', 
      submenuId: '<', 
     }, 
     controllerAs: 'itemVm', 
     controller: ['LogService', menuCtrl] 
    }); 

    function menuCtrl($scope, LogService) { 

     var itemVm = this; 
    } 

这里是showOrHideSub()函数在父控制器:

vm.showOrHideSub = function (submenu) { 
     console.log(submenu); 
     switch (submenu) { 
      case 'menuItemDivPositions': 
       console.log('position'); 
       break; 
      case 'menuItemDivOther': 
       console.log('other'); 
       break; 
     } 
    } 

我知道在指令中,执行此操作的方式是通过诸如showOrHideSub =“item.showOrHideSub({item:item.id})之类的对象映射”,但它似乎不适用于组件。

回答

1

如果您使用的是组件,您必须以组件的方式进行操作。 看起来你有组件的层次结构(子/父)。

家长内部的功能和属性可由子女使用require继承。

require: { 
    parent: '^^parentComponent' 
} 

这样,如果父定义一个函数showOrHideSub,孩子们可以把它直接使用this.parent.showOrHideSub(xxx)

这不是解决你的问题的唯一方法,但是这是对正道™你选择的架构。

var parentComponent = { 
 
    bindings: {}, 
 
    controller: ParentController, 
 
    template: ` 
 
     <li ng-repeat="item in $ctrl.menuItems"> 
 
     <child-component item="item"></child-component> 
 
     </li> 
 
    ` 
 
}; 
 
var childComponent = { 
 
    bindings: { 
 
     item: '<' 
 
    }, 
 
    require: { 
 
     parent: '^^parentComponent' 
 
    }, 
 
    controller: ChildController, 
 
    template: '<button ng-click="$ctrl.buttonClick($ctrl.item.id);">{{$ctrl.item.name}}</button>' 
 
}; 
 
function ParentController() { 
 
    this.menuItems = [{id:1, name:"item1"},{id:2, name:"item2"}]; 
 
    this.showOrHideSub = function(param) { 
 
    console.log("parent function called with param: " + param); 
 
    } 
 
} 
 
function ChildController() { 
 
    var vm = this; 
 
    this.buttonClick = function(id) { 
 
    vm.parent.showOrHideSub(id); 
 
    } 
 
} 
 

 
angular.module('app', []); 
 
angular.module('app') 
 
    .component('parentComponent', parentComponent) 
 
    .component('childComponent', childComponent);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script> 
 
<div ng-app="app"> 
 
    <parent-component></parent-component> 
 
</div>

+0

谢谢你这么多。有效 :) –

0

在下面的代码中将'item'更改为'vm'。您正在绑定项目功能'showOrHideSub(item.id)',它不存在。这是更新的代码。

<li ng-repeat="item in vm.menuItems"> 
    <menu-item-comp id="item.id" showOrHideSub="vm.showOrHideSub(item.id)" /> 
</li>