如何将带参数的函数传递给组件?

How can I pass a function with argument to a component?

我想将一个函数从父组件传递给子组件,并给它一个参数,该参数也已从父组件传递给子组件。 (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})" 但它似乎在组件中不起作用。

在下面的代码中将 'item' 更改为 'vm'。您正在绑定不存在的项目函数“showOrHideSub(item.id)”。这是更新的代码。

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

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

使用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>