我正在尝试将对象作为参数之一传递给我的ui路由器状态:

JS:

.state('graph', {
  name: 'Graph',
  url: "/graph?{friends}&{start}&{end}",
  templateUrl: 'templates/graphs.html',
  controller: 'GraphController'
})


HTML:

<a ui-sref="graph({friends: test.friends, start: test.start_date, end: test.end_date})">
  My Graphs
</a>


测试:

{
  friends: {
    'friend1': [MORE_DATA],
    'friend2': [MORE_DATA]
  },
  start_date: "Jun-17",
  end_date: "Jun-19"
}


但是,当我尝试访问控制器中的$stateParams时,它会打印出字符串"[object Object]"。如何获取要传递的test.friends对象?

最佳答案

您不能在查询字符串上传递对象,因此构造graph状态的URL的方式导致该对象转换为您看到的[object Object]字符串。

相反,您应该为状态创建params,如下所示。这将允许您传递对象并通过$stateParams在控制器中对其进行访问。



angular.module('app', ['ui.router'])
  .config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise("/");
    $stateProvider
      .state('main', {
        url: '/',
        template: '<div><a ui-sref="graph({friends: main.friends, start: main.start_date, end: main.end_date})">Go to graph</a></div>',
        controller: 'MainController as main'
      })
      .state('graph', {
        url: '/graph',
        template: '<div>Graph</div><div>{{graph.friends}}</div><div>Start: {{graph.startDate}}, End: {{graph.endDate}}',
        controller: 'GraphController as graph',
        params: {
          friends: null,
          start: null,
          end: null
        }
      });
  })
  .controller('MainController', function() {
    var _this = this;
    _this.friends =
      {
        'friend1': 'friend 1',
        'friend2': 'friend 2'
      };
    _this.start_date = "Jun-17";
    _this.end_date = "Jun-19";
  })
  .controller('GraphController', function($stateParams) {
    var _this = this;
    _this.friends = $stateParams.friends;
    _this.startDate = $stateParams.start;
    _this.endDate = $stateParams.end;
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
<div ng-app="app">
  <div ui-view></div>
</div>

10-07 19:58
查看更多