user1049558
user1049558

Reputation: 23

Passing multiple ids via route in angular JS

I have to pass multiple ids to a service via route. Right now the route works for a single id, but as a beginner to angular JS, I don't know how to pass multiple ids or is there a way where I can pass an array of ids via route? I am stuck and looking for some assistance

current route config

.when('/search/:id')

Expecting

.when('/search/:id/:id/:id')

or .when('/search/ids[]')

Thanks for the help in advance.

Upvotes: 2

Views: 1744

Answers (2)

Liviu T.
Liviu T.

Reputation: 23664

This is what I came up with. It's by no means perfect or bulletproof but it's a start.

Demo

PS: I only used the same controller for conveniance

app.config(['$routeProvider', function($routeProvider) {
  $routeProvider
   .when('/home:matrix', {templateUrl: 'home.html', controller: 'MainCtrl'})
   .when('/about:matrix', {templateUrl: 'about.html', controller: 'MainCtrl'});
}]);

function extractMatrixParams(matrix) {
  var matrixRegexp = /([^;=]+)=([^;]+)/g;
  var matrixParams = {};
  var match = matrixRegexp.exec(matrix);
  while(match) {
    var p = matrixParams[match[1]];
    if(p) {
      if(angular.isArray(p)) {
        p.push(match[2]);
      }
      else {
        matrixParams[match[1]] = [p, match[2]];
      }
    }
    else {
      matrixParams[match[1]] = match[2];
    }
    match = matrixRegexp.exec(matrix);
  }
  return matrixParams;
}

app.controller('MainCtrl', ['$scope', '$routeParams',
function($scope, $routeParams) {
  var matrixPrams = extractMatrixParams($routeParams.matrix);

  $scope.ids = matrixPrams.ids;
  $scope.myVar = matrixPrams.myVar;
  $scope.matrixPrams = matrixPrams;

  $scope.routeParams = $routeParams;
}]);

Upvotes: 0

Antonio Madonna
Antonio Madonna

Reputation: 919

Use .when('/search/:id1/:id2/:id3') or separate multiple ids with comma or other char.

Upvotes: 2

Related Questions