将对象作为参数传递给Angular ui-router

时间:2017-06-26 19:23:44

标签: javascript angularjs parameters angular-ui-router

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

JS:

;WITH CTE AS (
SELECT * FROM vw_Trades WHERE NOT (dtExpDate < GETDATE())
)
SELECT szSymbol, dtFwdDate, sum(fQuantity) 
FROM CTE GROUP BY szSymbol, dtFwdDate 
HAVING SUM(fQuantity) <> 0
ORDER BY szSymbol, dtFwdDate
GO

HTML:

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

TEST:

<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]"对象通过?

1 个答案:

答案 0 :(得分:1)

您无法在查询字符串上传递对象,因此构建graph状态的URL的方式会导致对象转换为您看到的字符串[object Object]

您应该为您的州创建params,如下所示。这将允许您传递对象,并通过$stateParams在控制器中访问它。

&#13;
&#13;
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;
  });
&#13;
<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>
&#13;
&#13;
&#13;