简体   繁体   中英

angularjs - passing objects between components

I am working on an AngularJS/Ui-router project. I have two states:

  • state1
  • state2 (a sub-state of state1)

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

<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>

How can I pass the state1data object to the state2 ? And what is the better way to do it? (In resolve of state2, or in controller of state2?)

A running plunker: 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.

app.component('state2cpt', {
  bindings : {
    state1data : '<'
  },
  templateUrl : '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

I would use parameters in the url, after all you use the ui-router to have states defined by your 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'
});

plunker: http://plnkr.co/edit/37e38xokN3bMrF64VZQ6?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM