0

Is there a way to get params in AngularJs 1.4 when the app runs, when the params come from get method? ex: http://www.myapp.com/whatever?param1=1234 I mean just here in my app.js file:

var myApplication = angular.module('App', [ui.router,...])
        .run(function ($rootScope,$http,....){
             var param = // I wish to read the param here
}

If not is possible, how can I get it using a controller? Thanks

2
  • You can use $stateProvider to define states with parameters. Check this out: scotch.io/tutorials/3-simple-tips-for-using-ui-router Commented Nov 11, 2016 at 0:07
  • Thanks, I solved using $locatio.search(). It returns an object with the params. Commented Nov 14, 2016 at 11:32

2 Answers 2

0

If your route was configured to receive that parameters you can observe $stateChangeStart

$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
console.log(toParams);
}

If not, there is a workaround (works perfectly :D):

One by one

function getParamByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

getParamByName('param1');

Or all

function getQueryParams(qs) {
    qs = qs.split('+').join(' ');
    var params = {},
        tokens,
        re = /[?&]?([^=]+)=([^&]*)/g;
    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    }
    return params;
}

console.log(getQueryParams(document.location.search));
Sign up to request clarification or add additional context in comments.

Comments

0

Good morning, Using $location.search() returns an object with the paramenters.Thanks!

Comments