[英]angularjs - passing objects between components
我正在研究AngularJS / Ui-router项目。 我有两种状态:
国家代码:
app.config(function($stateProvider){
$stateProvider.state('state1', {
url : '/state1',
component : 'state1cpt',
resolve : {
state1data : function(){
return {'x':1, 'y':2, 'z':3};
}
}
});
$stateProvider.state('state1.state2', {
url : '/state2',
component : 'state2cpt'
});
});
每个州都有一个组成部分:
app.component('state1cpt', {
bindings : {
state1data : '<'
},
templateUrl : 'state1.html'
});
app.component('state2cpt', {
templateUrl : 'state2.html'
});
和意见:
的index.html
<a ui-sref="state1">State1</a>
<ui-view></ui-view>
state1.html
<h2>State1 x: {{$ctrl.state1data.x}}</h2>
<a ui-sref="state1.state2">State2</a>
<ui-view></ui-view>
state2.html
<h2>State2</h2>
如何将state1data对象传递给state2 ? 更好的方法是什么? (在状态2的解析中,还是在状态2的控制器中?)
正在运行的插件: http ://plnkr.co/edit/HDt0f4wzjyUVQ7lEI9YB?p=preview
只需在组件定义中使用绑定-来自父状态的已解析state1data
仍将在所有子状态中可用。
app.component('state2cpt', {
bindings : {
state1data : '<'
},
templateUrl : 'state2.html'
});
state2.html
<h2>State2</h2>
<pre>{{$ctrl.state1data | json}}</pre>
或者如果您不想使用绑定-您可以在state2cpt
控制器中注入state1data
我将在url中使用参数,毕竟您使用ui-router具有由url定义的状态。
HTML
<a ui-sref="state1({x:1,y:2,z:3})">State1</a>
<a ui-sref="state1.state2({x:3,y:4,z:3})">State2</a>
JS
app.config(function($stateProvider){
$stateProvider.state('state1', {
url : '/state1/{x:int}/{y:int}/{z:int}',
component : 'state1cpt'
});
$stateProvider.state('state1.state2', {
url : '/state2/{x:int}/{y:int}/{z:int}',
component : 'state2cpt'
});
});
app.component('state1cpt', {
templateUrl : 'state1.html',
controller: function($stateParams){
this.x = $stateParams.x;
this.y = $stateParams.y;
this.z = $stateParams.z;
}
});
app.component('state2cpt', {
templateUrl : 'state2.html'
});
塞子: http ://plnkr.co/edit/37e38xokN3bMrF64VZQ6?p=preview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.