1

I have a url www.myurl.com/angularjs?var=myvar

I am just starting off with AngularJS (and javascript to be honest) and am trying to get the value of 'var' and pass it to my controller but I have no idea how to access the url variables

This is my controller...

vdApp.controller('ApplicantCtrl', ['$scope', '$http', function($scope, $http) {
    $http.post('http://www.myurl.com/services', iWantToPassMyDataHere).success(function(data)
    {
        $scope.results = data;
    });
}]);

How can I do this?

Thanks

1

4 Answers 4

2

You should use $location's search() method for that:

vdApp.controller('ApplicantCtrl', ['$scope', '$http', '$location', function($scope, $http, $location) {
    $http.post('http://www.myurl.com/services', $location.search()).success(function(data) {
        $scope.results = data;
    });
}]);
Sign up to request clarification or add additional context in comments.

1 Comment

Hi there, thanks for the response! I've tried that and it's not returning any results. I think it's because it's not passing the parameter to my endpoint. How can I check if it? I've tried setting $scope.myVar = $location.search() and it's just empty. Any ideas?
0

document.location.search returns the query string from the url

Comments

0

Use location.search and split out the query string like this:

var queryVals = location.search.split('&');
var v = queryVals[0].split('=')[1];

This is assuming that your query parameter, var, is the first parameter.

Comments

0

You get problems with # If you don't use regex.

var get = getUrlVars();
function getUrlVars() {
    var vars = {};
    /*Splits the variables into chuncks*/
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
        /*Takes those chunks and removes anything after the hashtag*/
        vars[key] = value.replace(/#\b[^#]*$/gi, '');
    });
    return vars;
}

This changes

http://www.yourdomain.com/account/products/productEdit.php?product_key=2edc8450-e75b-11e4-97c1-d02788bb017c

to

get.product_key = '2edc8450-e75b-11e4-97c1-d02788bb017c'

And

http://www.yourdomain.com/account/products/productEdit.php?product_key=2edc8450-e75b-11e4-97c1-d02788bb017c#inventory

to

get.product_key = '2edc8450-e75b-11e4-97c1-d02788bb017c'

Use this site to explore regular expressions. http://regexr.com/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.