Angular $routeParams: get query parameter as array

musa picture musa · Apr 11, 2015 · Viewed 15.9k times · Source

When I have multiple id parameters in query, $routeParams.id gives me an array. That's great. But, if only one id is present in the query, I get a string.

/?id=12&id=34&id=56    // $routeParams.id = ["12", "34", "56"]
/?id=12                // $routeParams.id = "12"

This is bad. Because in the first case, $routeParams.id[0] gives "12", while in the second one, it gives "1" (first char of "12").

I can work this around by inserting an empty id= to all my links, but this is ugly.

See in Plunker

Is "type-checking in controller" my only option? If so, how do I do it?

index.html:

<html ng-app="app">
<head>
  <script src="//code.angularjs.org/1.3.15/angular.js"></script>
  <script src="//code.angularjs.org/1.3.15/angular-route.js"></script>
  <script src="script.js"></script>
</head>

<body>
  <div ng-view></div>
</body>
</html>

home.html:

<a href="#/?id=12">#/?id=12</a><br/>
<a href="#/?id=12&id=34&id=56">#/?id=12&id=34&id=56</a><br/>
<a href="#/?id=12&id=">#/?id=12&id=</a><br/>

<pre>id: {{id | json:0}}</pre>
<pre>id[0]: {{id[0] | json}}</pre>

script.js:

angular.module('app', ['ngRoute'])

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

.controller('HomeCtrl', [
    '$scope', '$routeParams',
    function($scope, $routeParams) {
        $scope.id = $routeParams.id;
    }
]);

EDIT: For those who wonder, what I am trying to achive is: inter-controller (or inter-view) communication. User selects some items in one view, and sees details for those selected items in the next view. See in Plunker.

Answer

codegaze picture codegaze · Apr 11, 2015

The best way to do it is not to use id param multiple times but separate your values with another character and always get an array and you are ready to go!

script.js

(function() {
    var app = angular.module('app', ['ngRoute']);

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


    app.controller('HomeCtrl', [
        '$scope', '$routeParams',
        function($scope, $routeParams) {
            $scope.id = $routeParams.id.split('-');
        }
    ]);
})();

home.html

<p>
    <a href="#/?id=12-34-56">#/?id=12-34-56</a> Array
</p>

<p>
    <a href="#/?id=12">#/?id=12</a> Array
</p>


<pre>id: {{id | json:0}}</pre>

<pre>id[0]: {{id[0] | json}}</pre>