我按以下顺序拥有3个组件:1个具有2个子组件的父组件。我需要在父组件中运行一个函数,方法是从两个子组件中的任何一个启动它。
两个子组件js
文件如下所示:
angular
.module('app)
.component(childComponent1, {
bindings: {
switch: '&'
},
templateUrl: '...',
controller: ['$scope', function ($scope) {
}]
});
angular
.module('app)
.component(childComponent2, {
bindings: {
switch: '&'
},
templateUrl: '...',
controller: ['$scope', function ($scope) {
}]
});
父组件:
angular
.module('app)
.component(parentComponent, {
bindings: {
switch: '&'
},
templateUrl: '...',
controller: ['$scope', function ($scope) {
this.switch = function(){
'some code...'
}
}]
});
在每个子组件模板中都有一个按钮,它应该运行父函数switch
,如下所示:
<button class="btn" ng-click="$ctrl.switch()">Back</button>
代码不起作用,有什么建议吗?
答案 0 :(得分:1)
不是使用绑定,而是尝试在子节点中使用必需的param以访问父组件控制器。
require: {
parentCtrl: '^parentComponent'
},
有关此方法的示例,请查看https://plnkr.co/edit/fPGuZzIqNbfXeBGXve4J?p=preview。
此外,如果使用.component尝试使Angular 1.5更容易升级到Angular 2.0,您还应该尝试避免在组件控制器中使用$ scope。