【问题标题】:angularjs - passing objects between componentsangularjs - 在组件之间传递对象
【发布时间】:2017-03-30 19:04:47
【问题描述】:

我正在开发一个 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?更好的方法是什么? (在 state2 的解析中,还是在 state2 的控制器中?)

一个正在奔跑的笨蛋:http://plnkr.co/edit/HDt0f4wzjyUVQ7lEI9YB?p=preview

【问题讨论】:

    标签: javascript angularjs angular-ui-router


    【解决方案1】:

    只需在组件定义中使用绑定 - 从父状态解析的 state1data 仍将在所有子状态中可用。

    app.component('state2cpt', {
      bindings : {
        state1data : '<'
      },
      templateUrl : 'state2.html'
    });
    

    state2.html

    <h2>State2</h2>
    <pre>{{$ctrl.state1data | json}}</pre>
    

    或者如果您不想使用绑定 - 您可以在 state2cpt 控制器中注入 state1data

    【讨论】:

      【解决方案2】:

      我会在 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'
      });
      

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

      【讨论】:

        猜你喜欢
        • 2021-07-20
        • 2016-07-22
        • 1970-01-01
        • 2020-02-05
        • 1970-01-01
        • 2019-01-06
        • 2015-01-10
        • 2018-01-31
        • 1970-01-01
        相关资源
        最近更新 更多