簡體   English   中英

angularjs-在組件之間傳遞對象

[英]angularjs - passing objects between components

我正在研究AngularJS / Ui-router項目。 我有兩種狀態:

  • 狀態1
  • state2(state1的子狀態)

國家代碼:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM