当我使用ui-router状态时,如何将回调从父状态传递给子组件?
实施例
$stateProvider
.state('main', {
url: '/',
component: components.intro.name,
})
.state('main.root', {
url: '/main/',
component: components.main.name,
})
main
组件将有一个方法this.callback
。我想将其传递到main.root
状态。从我的测试来看,孩子状态只能得到结果吗?
答案 0 :(得分:0)
I made a Plunker to show the implementation of your question.
只有ui-router 1.0.3 ^具有您正在寻找的功能。在父组件的控制器中定义回调:
angular.module('app')
.component('main', {
controller: function() {
this.handleClickInParent = function () {
// this is the cb we're going to pass to the child
alert('Callback got clicked.');
};
},
template: `
<div>
<p>Parent Template: main</p>
<ui-view on-button-click=$ctrl.handleClickInParent></ui-view>
</div>
`
});
查看模板。回调传递给ui-view,子视图将在其中呈现。当子组件处于活动状态时,它将收到$ctrl.handleClickInParent
回调。但是,子组件必须是&#34; listen&#34;回调:
angular.module('app')
.component('nestedChild', {
bindings: {
// this binding is where the child is "listening"
onButtonClick: '<'
},
controller: function() {
console.log(this.onButtonClick);
// alert fn from parent
// the child template can access this callback as $ctrl.onButtonClick()
},
template: `
<div>
<p>Child Template: nestedChild</p>
<button ng-click=$ctrl.onButtonClick()>Click me to trigger passed callback</button>
</div>
`,
});
关于如何将ui-router迁移到Angular 1.5的组件here,这是一个很好的例子。他们使用&#39;&amp;&#39;相反,对于功能绑定,我找到了单向&#39;&lt;&#39;符号要简单得多。