【问题标题】:AngularJS - Passing a function from a parent to a child's class controller through bindingAngularJS - 通过绑定将函数从父级传递到子级控制器
【发布时间】:2019-06-04 02:02:09
【问题描述】:

我正在使用 AngularJS 1.7,并且我的代码基于以下 Todd Motto 风格指南:https://github.com/toddmotto/angularjs-styleguide

我想通过绑定将一个函数从我的父组件传递给一个子组件,如果我控制台记录它,我会得到一个函数,但我似乎无法在控制器上调用它。

这是我的代码:

parent.html

<child functionToRun="$ctrl.print(message)"></child>

parentController.js

export class ParentController {
  contructor($log) {
    'ngInject';
    this.$log = $log;
  }

  print(message) {
    console.log(message);
  }
}

child.component.js

import { ChildController } from './child.controller';
import templateUrl from './child.html';

export const ChildComponent = {
    templateUrl,
    controller: ChildController,
    bindings: {
        functionToRun: '&'
    }
};

childController.js

export class ChildController {
  constructor() {
    'ngInject';
  }

  $onInit() {
    this.functionToRun.call(this, 'hello');
  }
}

我搜索了一个类似的问题,但找不到任何问题,如果已经有的话,抱歉。

这可能吗? (我想在控制器上调用它,而不是在 HTML-$scope 上)

如果是这样,你能告诉我我的错误吗? 谢谢,不胜感激

【问题讨论】:

  • 尝试像这样传递它:&lt;child function-to-run="$ctrl.print(message)"&gt;&lt;/child&gt;
  • 另外,孩子可能需要用一个对象来调用它,比如this.functionToRun({ message: 'hello' })
  • 非常感谢@FrankModica!成功了,非常感谢!

标签: javascript angularjs binding parent-child


【解决方案1】:

使用连字符传递函数,如下所示:

<child function-to-run="$ctrl.print(message)"></child>

然后用一个对象调用函数:

this.functionToRun({ message: 'hello' });

【讨论】:

    猜你喜欢
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多