[英]angularjs - passing objects between components
I am working on an AngularJS/Ui-router project. 我正在研究AngularJS / Ui-router项目。 I have two states:
我有两种状态:
States code: 国家代码:
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'
});
});
Each state has a component: 每个州都有一个组成部分:
app.component('state1cpt', {
bindings : {
state1data : '<'
},
templateUrl : 'state1.html'
});
app.component('state2cpt', {
templateUrl : 'state2.html'
});
And the views: 和意见:
index.html 的index.html
<a ui-sref="state1">State1</a>
<ui-view></ui-view>
state1.html state1.html
<h2>State1 x: {{$ctrl.state1data.x}}</h2>
<a ui-sref="state1.state2">State2</a>
<ui-view></ui-view>
state2.html state2.html
<h2>State2</h2>
How can I pass the state1data object to the state2 ? 如何将state1data对象传递给state2 ? And what is the better way to do it?
更好的方法是什么? (In resolve of state2, or in controller of state2?)
(在状态2的解析中,还是在状态2的控制器中?)
A running plunker: http://plnkr.co/edit/HDt0f4wzjyUVQ7lEI9YB?p=preview 正在运行的插件: http ://plnkr.co/edit/HDt0f4wzjyUVQ7lEI9YB?p=preview
Just use a binding in component definition - still the resolved state1data
from parent state will be available in all child states. 只需在组件定义中使用绑定-来自父状态的已解析
state1data
仍将在所有子状态中可用。
app.component('state2cpt', {
bindings : {
state1data : '<'
},
templateUrl : 'state2.html'
});
state2.html state2.html
<h2>State2</h2>
<pre>{{$ctrl.state1data | json}}</pre>
or if you dont want to use binding - you can inject state1data
in state2cpt
controller 或者如果您不想使用绑定-您可以在
state2cpt
控制器中注入state1data
I would use parameters in the url, after all you use the ui-router to have states defined by your url. 我将在url中使用参数,毕竟您使用ui-router具有由url定义的状态。
html 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 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'
});
plunker: http://plnkr.co/edit/37e38xokN3bMrF64VZQ6?p=preview 塞子: http ://plnkr.co/edit/37e38xokN3bMrF64VZQ6?p=preview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.