AngularJS - 通过绑定将函数从父级传递给子级的 class 控制器
AngularJS - Passing a function from a parent to a child's class controller through binding
我正在使用 AngularJS 1.7,我的代码基于以下 Todd Motto 风格指南:https://github.com/toddmotto/angularjs-styleguide
我想通过绑定将一个函数从我的父组件传递给一个子组件,如果我 console.log 我得到一个函数,但我似乎无法在控制器上调用它。
这是我的代码:
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 上)
如果是这样你能告诉我我的错误吗?
谢谢,欣赏
使用连字符传递函数,像这样:
<child function-to-run="$ctrl.print(message)"></child>
然后用对象调用函数:
this.functionToRun({ message: 'hello' });
我正在使用 AngularJS 1.7,我的代码基于以下 Todd Motto 风格指南:https://github.com/toddmotto/angularjs-styleguide
我想通过绑定将一个函数从我的父组件传递给一个子组件,如果我 console.log 我得到一个函数,但我似乎无法在控制器上调用它。
这是我的代码:
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 上)
如果是这样你能告诉我我的错误吗? 谢谢,欣赏
使用连字符传递函数,像这样:
<child function-to-run="$ctrl.print(message)"></child>
然后用对象调用函数:
this.functionToRun({ message: 'hello' });