javascripthtmlangularjsangular-materialrouteparams

angularJS set route params in controller


I have an app which creates several surveys with random survey ids. As the ids are generated in the backend they are set in the controller. I read the documentation on that, however I do not really understand how to set the routeparams in order to always reach the page /survey/:surveryID.

Here is my code so far:

App Config:

...
 .when('/survey/:surveyId', {
        templateUrl: 'views/survey.html',
        controller: 'SurveyCtrl',
        controllerAs: 'survey'
      })

Controller:

function SurveyCtrl($scope, RequestService, _, $location, $routeParams) {

  $scope.go = function () {
    $location.path('/#/survey/' + Math.random());
  };
}

View with the link to /survey/:surveyId:

  <div>
    <md-button ng-click="go()">Enter Survey</md-button>
  </div>

I know that this is not the right way and it is not even working. Can someone tell me how to dynamically create these params and set them in the controller so I can access the link with a button and then when clicked reach the survey/:surveyId page?


Solution

  • To get your work done,

    $location.path('/survey/' + Math.random());
    

    You can use search method to pass params as well,

    $location.path('/myURL/').search({param: 'value'});
    

    $location methods are chainable.

    this produce :

    /myURL/?param=value