Get all scope variables from query parameters Get all scope variables from query parameters angularjs angularjs

Get all scope variables from query parameters


Ok, for starters, you can simply grab the values using the $location service

var search = $location.search();// should look like// {//     "opt.val": "true",//     "eg": "foobar"// }

Next, you can use the $parse service to assign the values to your $scope

angular.forEach(search, function(val, key) {    $parse(key).assign($scope, val);});

Keep in mind that every value in $location.search() is a string, including "true" and "false" so you may need some extra logic to handle those if you want Boolean values. Maybe something like this

angular.forEach(search, function(val, key) {    var evald = $scope.$eval(val);    if (evald !== undefined) {        val = evald;    }    $parse(key).assign($scope, val);});

Plunker demo ~ http://plnkr.co/edit/xOnDdWUW8PgsMFgmXr0r?p=preview


There are some ways you can do that:

#1 Using $StateParams

If you are using URLRouting of angular, you can use $stateParams which returns exactly what you want. All you have to do, is define your parameters in your Router. Example:

$stateProvider.state('contacts.detail', {    url: "/contacts?myParam&myParam2",    templateUrl: 'contacts.detail.html',    controller: function ($stateParams) {        // If we got here from a url of /contacts/42        expect($stateParams).toBe({contactId: "42"});    }})

This defines your route contacts receiving myParam and myParam2. After this, you can use $stateParamsService to parse this parameters in your controller very easy:

controller: function($stateParams){  $stateParams.myParam //*** Exists! ***// }

#2 Using $location

If you aren't using routes, and want more low-level service, you can inject $location in your controller and service, and parse the querys, eg:

var paramValue = $location.search().myParam; 

But it is necessary to enable html5mode first, and it will work

$locationProvider.html5Mode(true);

Hope it helps


Angular way would be. Just inject $routeParams in your controller.

See example below

// Given:// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby// Route: /Chapter/:chapterId/Section/:sectionId//// Then$routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}

See more details here $routeParams