Pass object as param into Angular ui-router

Issue

I’m trying to pass an object as one of the parameters to my ui-router state:

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>

TEST:

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

However, when I try to access $stateParams in the controller, it prints out the string "[object Object]". How can I get the test.friends object to be passed through?

Solution

You can’t pass objects on the querystring so the way you have constructed the URL for your graph state is causing the object to be converted to a string which you are seeing as [object Object].

What you should do instead is create params for your state as shown below. This will allow you to pass the object and have it accessible in your controller via $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>

Answered By – Lex

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.